在给定的时间间隔内尽可能多次调用一个函数。

huangapple go评论60阅读模式
英文:

Calling a function as many times as possible in a given time interval

问题

我正在尝试在给定的时间间隔内尽可能多次地调用函数 test()

这里该函数应该运行15秒。

function test(): void; // 仅类型定义

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

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

然而,该函数不会停止运行,并且 结束 的控制台日志不会出现(显然 Promise 没有被解决)。在JavaScript中是否有实现这个的方法?

我在想,我可能可以使用控制台计时器,并将条件放在 while 语句中?(但这是最好的方法吗?)

英文:

I am trying to call the function test() as many times as possible in a given time interval.

Here the function should be running for 15 seconds.

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. (Promise not resolved obviously). Is there a way to achieve this in Javascript ?

I was wondering, I could probably use console timers and put the condition in the while statement ? (But is that the best way ?)

答案1

得分: 1

您的功能无法停止执行的原因是,解决Promise不会停止脚本执行。您想要的是在您的run()方法中的某处存储一个标志,以便在意图解决Promise时可以翻转该标志。

请参阅下面的概念验证:我将周期缩短为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); // 1.5秒
    
    const timer = setInterval(() => {
      if (shouldInvoke)
        test();
      else
        window.clearInterval(timer);
    }, 0);
  });
}

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

请注意,这是一个示例代码,用于说明如何停止执行Promise后的操作。

英文:

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.

See proof-of-concept below: I've shortened the period to 1.5s and added a dummy test() method just for illustration purpose:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let i = 0;
function test() {
   console.log(`test: ${i++}`);
}

function run() {
  return new Promise(resolve =&gt; {
    let shouldInvoke = true;
    setTimeout(() =&gt; {
      shouldInvoke = false;
      resolve();
    }, 1500); // 15 seconds
    
    const timer = setInterval(() =&gt; {
      if (shouldInvoke)
        test();
      else
        window.clearInterval(timer);
    }, 0);
  });
}

run()
  .then(() =&gt; {
    console.log(&#39;Ended&#39;);
  });

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月6日 21:25:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612950.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定