• 《javascript忍者秘籍》笔记



    第8章 驯服定时器和线程

    同时创建大量的定时器,将会在浏览器中增加垃圾回收任务发生的可能性。

    减少同时使用定时器的数量,将大大有助于解决这种问题,这就是为什么所有现代动画引擎都使用一种称为中央定时器控制(central timer control)的技术。

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

    每个页面在同一时间只需要运行一个定时器。

    可以根据需要暂停和恢复定时器。

    删除回调函数的过程变得很简单

    让我们看一个使用该技术来管理多个函数的例子,被管理的这些函数分别操作不同的动画属性。首先,创建一个定时器以及用于管理多个处理程序的函数,示例如下。

    1. <div id="box">Hello!div>
    2. <script>
    3. var timers = {
    4. timerID:0,
    5. timers:[],
    6. add:function(fn){
    7. this.timers.push(fn)
    8. },
    9. start:function(){
    10. debugger
    11. if (this.timerID) return;
    12. (function runText(){
    13. if(timers.timers.length>0){
    14. for(var i=0;itimers.length;i++){
    15. if(timers.timers[i]()===false){
    16. timers.timers.splice(i,1)
    17. i--
    18. }
    19. }
    20. timers.timerID = setTimeout(runText,0)
    21. }
    22. })()
    23. },
    24. stop:function(){
    25. clearTimeout(this.timerID)
    26. this.timerID = 0
    27. }
    28. }
    29. var box = document.getElementById("box"),x=0,y=20;
    30. timers.add(function(){
    31. box.style.left = x + "px";
    32. if(++x >50) return false
    33. })
    34. timers.add(function(){
    35. box.style.top = y +"px"
    36. y += 2
    37. if(y>120) return false
    38. })
    39. timers.start()
    40. script>


    第三部分 忍者训练

    9.1 代码求值机制

    9.1eval()方法的基本测试

    1. assert(eval("5 + 5 ")===10,
    2. "5 and 5 is 10")
    3. assert(eval("var ninja =5;")===undefined,
    4. "no value was returned")
    5. assert(ninja === 5,"the varia ninja was created")
    6. debugger
    7. (function(){
    8. eval("var ninja = 6;") // 分号一定要的
    9. debugger
    10. assert(ninja === 6,
    11. "evaluate within the current scope")
    12. })()
    13. assert(window.ninja ===5,
    14. "the global was unaffected")
    15. assert(ninja ===5,
    16. "the global was unaffected")

    9.2测试eval()的返回结果

    1. var ninja = eval("({name:'Ninjia'})")
    2. assert(ninja != undefined ,"the ninja was created!")
    3. assert(ninja.name === 'Ninjia',
    4. "and with the expected property")
    5. var fn = eval("(function(){return 'Ninja';})");
    6. assert(typeof fn === 'function',
    7. "the funciton was created")
    8. assert(fn() === 'Ninja',
    9. "and returns expected value")
    10. var ninja2 = eval("{name:'Ninjia'}")
    11. assert(ninja2 != undefined ,"the ninja2 was created!")
    12. assert(ninja2.name === 'Ninjia',
    13. "and with the expected property")
    14. console.log(ninja2.name);

     

    应该指出的是,任何不是简单变量、原始值、赋值语句的内容都需要在外面包装一个括号,以便返回正确的结果。

     

  • 相关阅读:
    DSP28335学习记录(四)——ADC、DMA
    Python入门教程47:史上最齐全的第三方模块库
    Vue前端打印print设置自定义参数
    Android音视频开发:MediaRecorder录制视频
    网络之物理层
    paddle篇---用yolov3训练自己的数据集
    运维工作的“本手、妙手、俗手”
    动画讲解TCP的3次握手,4次挥手,让你一次看明白
    【dotnet】Unity 两种打包方式解析(IL2CPP Mono)
    Pthread 并发编程(三)——深入理解线程取消机制
  • 原文地址:https://blog.csdn.net/u012687612/article/details/126146370