在多个定时器中使用中央定时器控制,可以带来很大的威力和灵活性

  1. 每个页面在同一时间只需要运行一个定时器。
  2. 可以更具需要暂停和恢复定时器
  3. 删除回调函数的过程变得很简单
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var timers = {
timerID: 0,
timers: [],

add: function(fn){
this.timers.push(fn);
},

start: function(){
if(this.timerID) return;
(function runNext(){
if (timers.timers.lenght > 0){
for(var i =0; i<timers.timers.lenghth;i++){
if(timers.timers[i] === false){
timers.timers.splice(i,1);
i--;
}
}
timers.timerID = setTimeout(runNext,0);
}
})();
},

stop: function(){
clearTimeOut(this.timerID);
this.timerID = 0;
}
}

使用:

1
<div id="box">hello</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var box = document.getElementById('box'),
x = 0,
y = 20;

timers.add(function(){
box.style.left = x + 'px';
if(++x > 50) return false;
});

timers.add(function(){
box.style.top = y + 'px';
y +=2;
if(y > 120) return false;
});

timers.start();