第8章 驯服定时器和线程
同时创建大量的定时器,将会在浏览器中增加垃圾回收任务发生的可能性。
减少同时使用定时器的数量,将大大有助于解决这种问题,这就是为什么所有现代动画引擎都使用一种称为中央定时器控制(central timer control)的技术。
在多个定时器中使用中央定时器控制,可以带来很大的威力和灵活性。
■ 每个页面在同一时间只需要运行一个定时器。
■ 可以根据需要暂停和恢复定时器。
■ 删除回调函数的过程变得很简单。
让我们看一个使用该技术来管理多个函数的例子,被管理的这些函数分别操作不同的动画属性。首先,创建一个定时器以及用于管理多个处理程序的函数,示例如下。
<div id="box">Hello!</div>
<script>
var timers = {
timerID:0,
timers:[],
add:function(fn){
this.timers.push(fn)
},
start:function(){
debugger
if (this.timerID) return;
(function runText(){
if(timers.timers.length>0){
for(var i=0;i<timers.timers.length;i++){
if(timers.timers[i]()===false){
timers.timers.splice(i,1)
i--
}
}
timers.timerID = setTimeout(runText,0)
}
})()
},
stop:function(){
clearTimeout(this.timerID)
this.timerID = 0
}
}
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()
</script>
第三部分 忍者训练
9.1 代码求值机制
9.1eval()方法的基本测试
assert(eval("5 + 5 ")===10,
"5 and 5 is 10")
assert(eval("var ninja =5;")===undefined,
"no value was returned")
assert(ninja === 5,"the varia ninja was created")
debugger
(function(){
eval("var ninja = 6;") // 分号一定要的
debugger
assert(ninja === 6,
"evaluate within the current scope")
})()
assert(window.ninja ===5,
"the global was unaffected")
assert(ninja ===5,
"the global was unaffected")
9.2测试eval()的返回结果
var ninja = eval("({name:'Ninjia'})")
assert(ninja != undefined ,"the ninja was created!")
assert(ninja.name === 'Ninjia',
"and with the expected property")
var fn = eval("(function(){return 'Ninja';})");
assert(typeof fn === 'function',
"the funciton was created")
assert(fn() === 'Ninja',
"and returns expected value")
var ninja2 = eval("{name:'Ninjia'}")
assert(ninja2 != undefined ,"the ninja2 was created!")
assert(ninja2.name === 'Ninjia',
"and with the expected property")
console.log(ninja2.name);
应该指出的是,任何不是简单变量、原始值、赋值语句的内容都需要在外面包装一个括号,以便返回正确的结果。