Javascript的setTimeOut和setInterval用法,setinterval用法

來源:互聯網
上載者:User

Javascript的setTimeOut和setInterval用法,setinterval用法

Javascript的setTimeOut和setInterval,都是用來處理延時和定時任務,比如開啟網頁一分鐘之後,自動關閉彈出的廣告;或者頁面每隔10秒鐘發送非同步請求擷取最新的資料等等。

1、setTimeOut ( ) 用法

用於在指定的毫秒數後調用函數或計算運算式,即內部的方法只執行一次。


可以使用window.settTimeout 或者 setTimeout,兩個寫法基本一致。

只不過window.setTimeout將setTimeout函數作為全域window對象的一個屬性來引用。

應用執行個體:

function reloadTimer(){// do something};// 調用倒計時方法方式1setTimeout("reloadTimer()", 1000);// 調用倒計時方法方式2setTimeout(reloadTimer, 1000);// 調用倒計時方法方式3(帶參數)setTimeout('reloadTimer('+"'"+param+"'"+')', 1000);// 直接調用setTimeout(function(){// do something}, 1000);

2、setInterval ( ) 用法

可參照指定的周期(以毫秒計)來調用函數或計算運算式

setInterval不停的調用函數,直到clearInterval ( ) 被調用或視窗被關閉。由setInterval返回的 ID 值可用作clearInterval方法的參數

setInterval函數的參數及用法和setTimeout函數一樣,每隔一定時間執行當中的方法。

應用執行個體,倒計時60s的功能:

var count = 60;var countdown = setInterval(function(){if(count <= 1){clearInterval(countdown);}else{count--;}}, 1000);
clearInterval(countdown)停止調用

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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