英文:
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 => {
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');
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论