Javascript promises setTimeout

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);
});
+4
source share
2

, :

function countDown(i) {
  return promise = new Promise( (resolve, reject) => {

    console.log(i--);

    if (i > 0) {
      setTimeout( () => {
        countDown(i).then(resolve);
      }, 1000);
    } else {
      resolve('counter finished:');
    }

  });

}

let counter = countDown(10);
counter.then( (msg) => {
  console.log(msg);
});
Hide result
+5

, async/await, .

, - Babel/ Typescript .. .

function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) }

async function countDown(i) {
  while (i > 0) {
    console.log(i--);  
    await sleep(1000);
  }
  return "counter finished:";
}

let counter = countDown(10);
counter.then( (msg) => {
  console.log(msg);
});
Hide result
+2

Source: https://habr.com/ru/post/1688244/


All Articles