简体   繁体   English

在给定的时间间隔内尽可能多地调用函数

[英]Calling a function as many times as possible in a given time interval

I am trying to call the function test() as many times as possible in a given time interval.我试图在给定的时间间隔内尽可能多地调用函数test()

Here the function should be running for 15 seconds.此处该函数应运行 15 秒。

function test(): void; // Only type def

function run() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, 15000); // 15 seconds
    while (true) {
      test();
    }
  });
}

run()
  .then(() => {
    console.log('Ended');
  });

However, the function doesn't stop running, and the Ended console.log does not appear.但是,该函数不会停止运行,并且不会出现Ended console.log。 (Promise not resolved obviously). (承诺没有明显解决)。 Is there a way to achieve this in Javascript ?有没有办法在 Javascript 中实现这一点?

I was wondering, I could probably use console timers and put the condition in the while statement ?我想知道,我可能可以使用控制台计时器并将条件放在 while 语句中? (But is that the best way ?) (但这是最好的方法吗?)

The reason why your function does not stop executing is because resolving a promise does not stop script executing.您的函数不会停止执行的原因是因为解析承诺不会停止脚本执行。 What you want is to store a flag somewhere in your run() method, so that you can flip the flag once the promise is intended to be resolved.你想要的是在你的run()方法中的某个地方存储一个标志,这样一旦承诺被解决,你就可以翻转标志。

See proof-of-concept below: I've shortened the period to 1.5s and added a dummy test() method just for illustration purpose:请参阅下面的概念验证:我已将周期缩短到 1.5 秒并添加了一个虚拟的test()方法仅用于说明目的:

 let i = 0; function test() { console.log(`test: ${i++}`); } function run() { return new Promise(resolve => { let shouldInvoke = true; setTimeout(() => { shouldInvoke = false; resolve(); }, 1500); // 15 seconds const timer = setInterval(() => { if (shouldInvoke) test(); else window.clearInterval(timer); }, 0); }); } run() .then(() => { console.log('Ended'); });

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

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