setTimeout()和setInterval(),settimeout

來源:互聯網
上載者:User

setTimeout()和setInterval(),settimeout

setTimeout()和setInterval()兩個方法都是JavaScript的計時事件

相同

1.兩者都為HTML DOM Window對象的兩個方法

使用可以寫成

window.setTimeout();

window.setInterval();

當然不加window也是可以的。

 

2.兩者都有兩個參數

setTimeout("javascript function",milliseconds);

setInterval("javascript function",milliseconds);

第一個參數是一個方法

第二個參數是間隔時間(毫秒)

 

不同

1.

   setTimeout();只執行一次,傳入一個毫秒數時間到達後執行一次傳入function函數,執行完後函數失效。

   setInterval(); 迴圈執行,在傳入毫秒間隔時間內迴圈執行傳入function函數,執行後不失效。(clearInterval() 方法用於停止 setInterval() 方法執行的函數代碼。 )

 

執行個體

實現倒數三秒後跳轉當前頁面,並在頁面顯示出倒數。

1.頁面

<body style="background-color : #EAEAEA; color :#A3A3A3"><div><span id="totalSecond">3</span>秒後自動返回首頁</div></body>


2.JS代碼

2.1 setTimeout();實現

 

function timeout() {var total = totalSecond.innerText; if(total <= 0) {location.href = "http://www.baidu.com";} else {totalSecond.innerText = --total;window.setTimeout("timeout()", 1000);}}window.setTimeout("timeout()", 1000);


 

2.2 setInterval();實現

function interval() {var total = totalSecond.innerText; if(total <= 0) {location.href = "http://www.baidu.com";} else {totalSecond.innerText = --total;}}window.setInterval("interval()", 1000); 


注意:

setTimeout和setInterval在頁面載入後會自動執行。所以不需要添加document.onload事件。

當然如果兩者需要調用function那麼調用的function必須要在setTimeout和setInterval代碼的前面。

因為js在頁面是自上而下啟動並執行,如果放在setTimeout和setInterval的後面則其調用的function為無效方法,程式就會出問題。

 如下就是錯誤

window.setInterval("interval()", 1000); function interval() {var total = totalSecond.innerText; if(total <= 0) {location.href = "http://www.baidu.com";} else {totalSecond.innerText = --total;}}


還有一個三秒後頁面跳轉的方法,在head標籤裡添加如下代碼,當然頁面秒數顯示還需要自己添加

<meta http-equiv="Refresh" content="3; url=http://www.baidu.com.cn" />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.