《Secrets of The Javascript Ninja》中的Central Timer Control会尽可能快地执行添加的函数。我如何使用中央计时器控制的想法,每250毫秒发生一些事情?如果我需要每250毫秒发生一件事每600毫秒发生另一件事呢?不知怎么的,我觉得我真的错过了这次机会。
对不起,我没有太多的时间来编写可读性好的代码,但是如果你运行这个脚本并在调试器中运行它,你就会知道如何在单线程环境中实现你想要的东西。请注意,使用Web Workers的解决方案可能会更好地工作,如果你想确保你会得到一个函数每250ms和另一个650ms呐喊,但是,我认为,不能再被称为中央定时器控制。
如果你将300传递给函数'one'的延迟函数,你就会明白为什么这个方法并不总是有效。
顺便说一句,Secrets of the Javascript Ninja是我读过的关于Javascript的最好的书。不错的选择。
var fns = [];
function delay(ms) { // you can set delay manually to see what happens if functions take longer to execute
ms += new Date().getTime();
while (new Date() < ms){}
}
var one = function(d) { // first function
console.log(new Date() - temp);
temp = new Date;
delay(100); // let's say our function takes approximately 100 ms to execute
}
var two = function(d) { // second function
console.log(new Date() - temp);
temp = new Date;
delay(150);
}
fns.push(one);
fns.push(two);
intervals = [250, 650];
var temp = new Date;
(function(fns, intervals) {
var count = 0,
start, finish, execTime; // helpers
(function run () {
start = new Date();
fns[count](); // function executes here
finish = new Date();
execTime = finish - start; // time that function takes to execute
setTimeout(run, ( (intervals[count] - execTime) > 0) ? intervals[count] - execTime : 0 ); // if function took too long to execute start as soon as you can, otherwise subtract execution time from the interval
if (count === intervals.length - 1) {
count = 0;
} else {
count++;
}
})()
})(fns, intervals) // passing array of function to execute and array of intervals