简体   繁体   English

javascript承诺setTimeout

[英]javascript promises setTimeout

I'm currently working on a slot machine effect for a website. 我正在为网站制作老虎机效果。 I use a function that calls itself several times with setTimeout(). 我使用一个用setTimeout()多次调用自己的函数。 I use setTimeout() and not a simple loop because I need the effect to slow down. 我使用setTimeout()而不是简单的循环,因为我需要效果减慢。 This is where the milliseconds come in handy. 这是毫秒派上用场的地方。 After this i want to fire the same function with different parameters. 在此之后我想用不同的参数激发相同的功能。 So I need to know when the first "loop" is done. 所以我需要知道第一个“循环”何时完成。 I tried promises for that. 我试过这个承诺。 With no success. 没有成功。

To simplify the problem, can someone tell me why the code below doesn't fire the .then() method? 为了简化问题,有人可以告诉我为什么下面的代码不会触发.then()方法吗? I'm new to all this programming and this is my first question here. 我是所有这些编程的新手,这是我的第一个问题。 I hope it's not an obvious mistake I make 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);
});

You simply need to resolve the promise after the recursive calls, like so: 您只需要在递归调用后解析承诺,如下所示:

 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); }); 

You might want to look into using async / await , here is your example using this. 你可能想要研究使用async / await ,这是你使用它的例子。

If you need to target old browser, you can also use something Babel / Typescript etc. But most modern browser already support this. 如果您需要定位旧浏览器,您还可以使用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); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM