中央定时器控制
浏览器不会对特定interval处理程序的多个实例进行队列
由于javascript在执行时,页面渲染的所有更新操作都要暂停,所有利用定时器分解长时间运行的任务,用于提升用户体验。
中央定时器:
1. 每个页面在同一时间只需要运行一个定时器
2. 可以根据需要暂停和恢复定时器
3.删除回调函数的过程变得简单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>timers</title>
</head>
<body>
<div id="box" style="display: inline-block; position: absolute;">hello</div>
</body>
<script>
window.onload=function(){
var timers = {
timerId: 0,
timers: [],
add: function(fn){
this.timers.push(fn);
},
start: function(){
if(this.timerId) return;
(function runNext(){
for(var i = 0; i < timers.timers.length; 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;
}
}
var box = document.getElementById('box'), x=0, y=0;
timers.add(function(){
box.style.left = x + 'px';
console.log('x')
if(++x > 50) return false;
});
timers.add(function(){
box.style.top = y + 'px';
console.log('y')
y += 2;
if(y > 120) return false;
});
timers.start();
}
</script>
</html>
在大多数情况下,是使用闭包来给定时器传递数据的,但现代浏览器(IE9以上),也允许我们在声明定时器的时候传入参数
for(var i =1 ; i< 4; i++){ setTimeout(function(i){console.log(i)},100,i) } for(var i =1 ; i< 4; i++){ (function(i){ setTimeout(function(){console.log(i)},100) }) } setTimeout(function runNext(){ console.log("In"); setTimeout(runNext, 10); },10)

浙公网安备 33010602011771号