javascript定時器小結

來源:互聯網
上載者:User

標籤:javascript   html   定時器   settimeout   setinterval   

javascript有兩種定顯示器, setTimeout和setInterval,下面簡要介紹兩個函數然後附上簡單的例子。
setTimeout(function, time) ,  當定位到time間隔則執行function函數,執行一次就不再執行

clearTimeout(t), 結束setTimeout定時器
setInterval(function, time), 每隔time間隔執行一次function函數

clearInterval(t),結束setinterval定時器
樣本:

<!DOCTYPE html><html><head><meta charset="utf-8"><title>JS Test</title><style type="text/css">.xxm {color:green;font:size=36px;font-weight:bold;font-family:Microsoft YaHei;background-color:whitebackground-position:top center;}</style></head><body><p class="xxm">定時器</p><script type="text/javascript">var c1 = 0;var c2 = 0;var t; var t2;var t3;function timeCount(){document.getElementById('txt').value = c1;c1 = c1 + 1;t = setTimeout("timeCount()", 1000); //此處實現timeCount函數每隔1s執行一次的功能}function stopTimeout(){clearTimeout(t);}function timeCount2(){document.getElementById('txt').value=c2;c2=c2+1;}function interval(){t2 = setInterval("timeCount2()", 1000);}function stop(){clearInterval(t2);}function startTime(){var today = new Date(); var y = today.getFullYear();var mon= today.getMonth();var day = today.getDate();var h = today.getHours();var m = today.getMinutes();var s = today.getSeconds();m = checkTime(m);s = checkTime(s);document.getElementById('txt').value = y+"-"+mon+"-"+day+" "+h+":"+m+":"+s;//t3 = setTimeout('startTime()',1000);}function start(){t3 = setInterval('startTime()',1000);}function stopTime(){//clearTimeout(t3);clearInterval(t3);}function checkTime(i){if (i<10){i = "0"+i;}return i;}</script><input type="text" id="txt"/><br><br><input type="button" value="開始setTimeout事件" onclick="javascript:timeCount()"/><input type="button" value="結束setTimeout事件" onclick="javascript:stopTimeout()"/><br><br><input type="button" value="開始setInterval事件" onclick="javascript:interval()"/><input type="button" value="結束setInterval事件" onclick="javascript:stop()"/><br><br><p class="xxm">系統時鐘<p/><input type="button" value="開始時間" onclick="javascript:start()"/><input type="button" value="結束時間" onclick="javascript:stopTime()"/><br><br></body></html>

樣本效果:


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

javascript定時器小結

聯繫我們

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