I am currently working on a slot machine effect for a website. I use a function that calls itself several times using setTimeout (). I use setTimeout () rather than a simple loop because I need the effect to slow down. Milliseconds come in handy here. After that, I want to run the same function with different parameters. Therefore, I need to know when the first "cycle" will be executed. I tried promises for this. Without success.
To simplify the problem, can someone tell me why the code below does not run the .then () method? I am new to all this programming and this is my first question. I hope this is not a clear mistake I am making here.
function countDown(i) {
return promise = new Promise( (resolve, reject) => {
console.log(i--);
if (i > 0) {
setTimeout( () => {
countDown(i);
}, 1000);
} else {
resolve('counter finished:');
}
});
}
let counter = countDown(10);
counter.then( (msg) => {
console.log(msg);
});
source
share