JavaScript[20] -- 定時器

定時器

都是不精確的
定時器裏的事件屬於下一次事件隊列,定時器時間再短,也是定時器後面的代碼先執行,而後纔是定時器裏面的代碼執行
每個定時器都對應這一個序號,從1開始排列,用後須要清除定時器

setTimeout()

  • 用來指定某個函數或字符串在指定的毫秒數以後執行,只會執行一次
  • 第一參數爲函數,做爲執行體,第二個參數爲執行間隔時間(毫秒)
    注意:對函數傳遞參數的時候,能夠把實參放在執行間隔時間的後面(不兼容IE9及如下,在IE裏面用閉包的形式去寫)

clearTimeout()

  • 清除定時器,參數爲定時器的名稱web

    <script>
        // 不兼容IE9及如下
        var timer1 = setTimeout(function(a, b){
            console.log(a + b);     // 3
        },1000,1,2);
    
        document.onclick = function(){
            clearTimeout(timer1);    // 清除計時器1
            clearTimeout(timer2);    // 清除計時器2
    
            console.log("中止定時器 " + timer1);    // 中止定時器 1   
            console.log("中止定時器 " + timer2);    // 中止定時器 2 
        }
    
        // 兼容IE9及如下的閉包寫法
        var timer2 = setTimeout((function(a, b){
            return function(){
                console.log(a + b); // 3
            }
        })(1,2),1000);
    </script>

setInterval()

  • setInterval()和setTimeout()同樣,可是會無限執行

clearInterval()

  • 參數爲定時器clearInterval()的名稱閉包

    <script>
        var str = "a";
        var obj = {
            str : "b",
            foo : func,
        }
        function func(){
            console.log(this.str);
        }
    
        let timer1 = setInterval(obj.foo,1000);     // a  不是b,函數做爲參數傳遞會形成隱式丟失,this指向Window
        let timer2 = setInterval(function(){
            console.log("b");
        },1000);
    
        document.onclick = function(){
            console.log("中止定時器");
            clearInterval(timer1);
            clearInterval(timer2);
        }
        console.log(timer1,timer2);     // 1 2  此行代碼優先於定時器裏的代碼執行
    </script>

案例

  • 5s後跳轉百度函數

    <div id="wrap">頁面將在<span>5s</span>以後跳轉</div>
    <script>
        let oSpan = document.getElementsByTagName("span")[0],
            num = 5;
        let timer = setInterval(function(){
            num --;
            oSpan.innerHTML = `${num}s`;
            if(num===0){
                window.open("http://www.baidu.com","_self");
                clearInterval(timer);
            }
        },1000);
    </script>

requestAnimationFrame()

  • 如今作動畫使用的幀函數(不兼容IE10及如下)
    注意:它除了在外部執行函數體,也要在執行函數體裏面本身執行
  • cancelAnimationFrame()清除定時器動畫

    <script>
        // 這是requestAnimationFrame的兼容寫法
        window.requestAnimationFrame = (function(){
           return  window.requestAnimationFrame ||
                   window.webkitRequsetAnimationFrame ||
                   window.mozRequestAnimationFrame ||
                   window.oRequestAnimationFrame ||
                   window.msRequestAnimationFrame ||
                   function(callback){
                       window.setTimeout(callback,1000/60);
                   };
       })();
       
       let a = 0;
       
       function func(){
           a++;
           console.log(a);
           requestAnimationFrame(func);
       }
       
       requestAnimationFrame(func);
    </script>
相關文章
相關標籤/搜索