JavaScript中關於setTimeout和setInterval的使用

來源:互聯網
上載者:User

兩個函數都是可以用來實現一段時間後執行一段javascript代碼的效果。兩個函數都有兩個參數,前面的都是執行運算式,後面的是隔的秒數。

不同的是setInterval會每隔指定的時間段就執行一次代碼,具有重複性。而setTimeout只會調用後執行一次。

下面通過函數的建立和函的自動刪除來深刻理解兩個函數;

1.函數的建立

setTimeOut的建立:

showTime();

function showTime()

{

    var today = new Date();

    alert("The time is: " + today.toString());

    setTimeout("showTime()", 5000);

}

調用函數後五秒鐘才會執行一次showtime函數

setInterval的建立

setInterval("showTime()", 5000);

function showTime()

{

    var today = new Date();

    alert("The time is: " + today.toString());

}

總結:貌似兩個函數的結果相似,其實不然第二個函數會反覆的報時,直到該網頁被關閉。

兩個函數的消除:

setTimeout的消除使用

clearTimeout()函數;調用的執行個體:

var timeoutProcess = setTimeout("alert('GOAL!')", 3000);

var stopGoalLink = document.getElementById("stopGoalLink");

attachEventListener(stopGoalLink, "click", stopGoal, false);//加入事件函數,參數為(目標;事件;調用的函數;是否冒泡)

function stopGoal()

{

    clearTimeout(timeoutProcess);

}

setInterval的消除

var timeoutProcess = setTimeout("alert('GOAL!')", 3000);

var stopGoalLink = document.getElementById("stopGoalLink");

attachEventListener(stopGoalLink, "click", stopGoal, false);//加入事件函數,參數為(目標;事件;調用的函數;是否冒泡)

function stopGoal()

{

    clearInterval(timeoutProcess);

}

相關文章

聯繫我們

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