设置和使用单个全局 setTimeout?
Setting and using a single Global setTimeout?
刚刚在 this very old question 中偶然发现一条关于清除所有 setTimeouts 的评论。
这个评论引起了我的兴趣,因为它实际上并没有直接解决这个问题,而是提供了一个非常有趣的替代解决方案来解决跟踪多个计时器的问题,但遗憾的是他没有提供如何实现这个问题的例子:
Use a global timeout which all of your other functions derive timing
from. This will make everything run faster, and be easier to manage,
although it will add some abstraction to your code...
... I just meant that you have one global timeout running once every
50ms. Every other function which would require a timing element would
then grab it from the global timeout. Google switched to this for
efficiency, although I can no longer find the article quoting it.
如何在全局 space 中设置我假设的命名计时器,然后在多种情况下在其他地方引用它?
例如,如果我们在全局 space 中有这样的东西:
let myGlobalTimer = setTimeout(function(){ myFunc(); }, 50);
那只会 运行 myFunc
每 50 毫秒。
我很确定你不能将动态函数名称传递给 setTimeout
那么如何实现这一点呢?
您可以在每次触发超时时通过数组或Set
函数设置超时运行。要添加一个每次迭代都获得 运行 的函数,请将其添加到 Set
;要从 运行ning 中阻止它,请将其从 Set
中删除。例如:
const fns = new Set();
function runAllTasks() {
for (const fn of fns) {
fn();
}
// Run every 500 ms:
setTimeout(runAllTasks, 500);
}
fns.add(() => console.log('fn one running'));
const fn2 = () => console.log('fn two running');
fns.add(fn2);
runAllTasks();
// example, remove fn2 from the Set after 1300ms:
setTimeout(() => {
fns.delete(fn2);
}, 1300);
当然,您也可以使用数组,但是当集合中项目的 顺序 无关紧要时,Set
更合适。
刚刚在 this very old question 中偶然发现一条关于清除所有 setTimeouts 的评论。
这个评论引起了我的兴趣,因为它实际上并没有直接解决这个问题,而是提供了一个非常有趣的替代解决方案来解决跟踪多个计时器的问题,但遗憾的是他没有提供如何实现这个问题的例子:
Use a global timeout which all of your other functions derive timing from. This will make everything run faster, and be easier to manage, although it will add some abstraction to your code...
... I just meant that you have one global timeout running once every 50ms. Every other function which would require a timing element would then grab it from the global timeout. Google switched to this for efficiency, although I can no longer find the article quoting it.
如何在全局 space 中设置我假设的命名计时器,然后在多种情况下在其他地方引用它?
例如,如果我们在全局 space 中有这样的东西:
let myGlobalTimer = setTimeout(function(){ myFunc(); }, 50);
那只会 运行 myFunc
每 50 毫秒。
我很确定你不能将动态函数名称传递给 setTimeout
那么如何实现这一点呢?
您可以在每次触发超时时通过数组或Set
函数设置超时运行。要添加一个每次迭代都获得 运行 的函数,请将其添加到 Set
;要从 运行ning 中阻止它,请将其从 Set
中删除。例如:
const fns = new Set();
function runAllTasks() {
for (const fn of fns) {
fn();
}
// Run every 500 ms:
setTimeout(runAllTasks, 500);
}
fns.add(() => console.log('fn one running'));
const fn2 = () => console.log('fn two running');
fns.add(fn2);
runAllTasks();
// example, remove fn2 from the Set after 1300ms:
setTimeout(() => {
fns.delete(fn2);
}, 1300);
当然,您也可以使用数组,但是当集合中项目的 顺序 无关紧要时,Set
更合适。