javascript定時器小結

來源:互聯網
上載者:User

javascript定時器小結

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

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

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

 


定時器

<script type=text/javascript>|r|var c1 = 0;|r|var c2 = 0;|r|var t; |r|var t2;|r|var t3;|r|function timeCount(){|r|document.getElementById('txt').value = c1;|r|c1 = c1 + 1;|r|t = setTimeout(timeCount(), 1000); //此處實現timeCount函數每隔1s執行一次的功能|r|}|r|function stopTimeout(){|r|clearTimeout(t);|r|}|r|function timeCount2(){|r|document.getElementById('txt').value=c2;|r|c2=c2+1;|r|}|r|function interval(){|r|t2 = setInterval(timeCount2(), 1000);|r|}|r|function stop(){|r|clearInterval(t2);|r|}|r|function startTime(){|r|var today = new Date(); |r|var y = today.getFullYear();|r|var mon= today.getMonth();|r|var day = today.getDate();|r|var h = today.getHours();|r|var m = today.getMinutes();|r|var s = today.getSeconds();|r|m = checkTime(m);|r|s = checkTime(s);|r|document.getElementById('txt').value = y+-+mon+-+day+ +h+:+m+:+s;|r|//t3 = setTimeout('startTime()',1000);|r|}|r|function start(){|r|t3 = setInterval('startTime()',1000);|r|}|r||r|function stopTime(){|r|//clearTimeout(t3);|r|clearInterval(t3);|r|}|r|function checkTime(i){|r|if (i<10){|r|i = 0+i;|r|}|r|return i;|r|}|r||r|</script>





系統時鐘


 

 

樣本效果:

 

聯繫我們

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