标签: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:white background-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 html 定时器 settimeout setinterval
原文地址:http://blog.csdn.net/xxm524/article/details/46848625