Javascript中的setTimeout,setInterval,requestAnimFrame

來源:互聯網
上載者:User

標籤:javascript   settimout   setinterval   

         這三種方法我們平時初學的時候可能容易混淆,下面我們將使用例子的形式來闡述這三種方法不同的用法。

         setTimeout:Calls a function or executes a code snippet after a specified delay.(在特定的時間後執行方法和代碼塊)

       文法:var timeID = setTimeout(func|code,delay) 

<script type="text/javascript">/*第一種寫法function f(){console.log("HI");}setTimeout(f,1000);*//*第二種寫法setTimeout("console.log('aaa')",2000);*/                                                                                                                                                        //第三種寫法setTimeout(function(){console.log("bbb")},2000);</script>
            在2秒之後執行輸出操作

          複雜一點例子:

<!DOCTYPE html><html><head><title></title><script type="text/javascript">/*延遲幾秒後調用該方法*/var timeoutID;function delayedAlert(){timeoutID = window.setTimeout(slowAlert,2000);}function slowAlert(){console.log("That was really show~");}function clearAlert(){window.clearTimeout(timeoutID);}</script></head><body><p>Live Example</p><button onclick="delayedAlert();">Show an alert box after two seconds</button><p></p><button onclick="clearAlert();">Cancel alert before it hanppeds</button></body></html>

       開啟頁面並開啟瀏覽器控制台,點擊"show an alert..." 按鈕,就看到我們在2秒後在控制台輸出"That was really show~~~"  點擊一次2秒後就輸出【可以點擊多次哦~】 

          點擊“Cancel alert before it happends” 按鈕後,就能夠取消正在執行的delayedAlert()方法【執行完列印輸出後就沒作用了~】


         讓我們再來看setInterval()方法

         setInterval() : Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.(在時間間隔內永久重複的執行函數和代碼塊,返回一個intervalID),下面是一個顏色變幻的例子:

<!DOCTYPE html><html><head><title></title><script type="text/javascript">    /*和前面的setTimeout 挺相像的有一個nItervId,清除的時候就用clearInterval(id)方法清除就可以了~    */var nIntervId;function changeColor(){nIntervId = setInterval(flashText,500);}function flashText(){var oElem = document.getElementById("my_box");oElem.style.color = oElem.style.color == "red" ? "blue" : "red";}function stopTextColor(){clearInterval(nIntervId);}</script></head><body onload="changeColor();"><div id="my_box"><p>Hello World!</p></div><button onclick="stopTextColor();">Stop</button></body></html>

        上述例子會在0.5秒後執行顏色變幻功能,並永久不斷的執行下去。當然我們點擊Stop按鈕,就可以停止顏色變幻,這裡的clearInterval(nIntervId) 是根據我們setInterval方法返回的ID來停止使用他們的。


         最後來說對我比較陌生的window.requestAnimFrame,這個方法給我們在繪製的過程中有一個平滑的過渡,這個方法的效能比setTimeout和setInterval要好點。所以接下來我們將介紹它怎麼使用。

<!DOCTYPE html><html><head><meta charset="utf-8"><title>startGirl</title></head><body onload="init()"><div><canvas id="canvas" width="800px" height="600px"></canvas></div><script type="text/javascript">/*拿到我想要的canvas*/var can;/*繪製2D圖形的context*/var ctx;/*定義寬高*/var w;var h;function init(){can = document.getElementById("canvas");ctx = can.getContext("2d");w = can.width;h = can.height;console.log("canvas w:"+w);console.log("canvas h:"+h);drawLoop();}function drawLoop(){window.requestAnimFrame(gameLoop);fillCanvas();}function fillCanvas(){ctx.fillStyle = "#393550";ctx.fillRect(0,0,w,h);}                                                                                                                                                         //瀏覽器的相容設定window.requestAnimFrame = (function() {return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {return window.setTimeout(callback, 1000 / 60);};})();</script></body></html>

        我們可以在這個網站看到setTimeout和requestAnimFrame績效參數的比較。http://ie.microsoft.com/testdrive/graphics/RequestAnimationFrame/Default.html#  

        tips :在我們實際項目繪畫的過程中,不推薦使用多個setInterval()或setTimeout()一起使用,他們會佔用CPU效能。

       轉載請註明出處:Coder的不平凡 http://blog.csdn.net/pearyangyang/article/details/45561115

     

      

Javascript中的setTimeout,setInterval,requestAnimFrame

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.