本文实例为大家分享了Javascript定时器使用的具体代码,供大家参考,具体内容如下
定时器分类
1、循环执行:一段程序能够每间隔一段时间执行一次【setInterval()】【clearInterval()】
2、定时执行(一次定时器):某一段程序需要在延迟多少时间后执行【setTimeout()】【clearTimeout()】
定时器使用
使用注意:为了防止定时器累加,使用定时器要先清除后设置;要保证内存中只有一个定时器。
1、循环执行:一段程序能够每间隔一段时间执行一次
设置定时器:【var timeid = window.setInterval(“方法名或方法”,“延时”);】
清除定时器【window.clearInterval(timeid);】
// window.setInterval("console.log('1秒打印一次')", 1000);
// setInterval(function() {
// console.log('1秒打印一次');
// }, 1000);
function test() {
console.log('1秒打印一次');
}
setInterval(test, 2000);
示例1:秒表计时
定时器计时 #box { width: 300px; height: 200px; border: 1px solid #ccc; margin: 20px auto; text-align: center; } .btn { width: 100%; margin: 10px; } .diaplayTime { font-weight: 600; font-size: 20px; margin-top: 30px; } 计时时间为: 0 秒
示例2:节假日倒计时
定时器-放假倒计时 #time { font-size: 30px; color: blue; text-align: center; }
注意:把总的秒数(allSecond)转化为 天(d)+时(h)+分(m)+秒(s)的形式,公式如下
d=parseInt(allSecond / 3600 / 24)
h=parseInt(allSecond / 3600 %24)
m=parseInt(allSecond / 60 %60)
s=parseInt(allSecond%60)
示例3:时钟
Title * { margin: 0; padding: 0; list-style: none; } #box { width: 600px; height: 600px; background: url("images/clock.jpg") no-repeat; margin: 10px auto; position: relative; } #hour, #min, #second { position: absolute; left: 50%; top: 0; width: 30px; height: 600px; margin-left: -15px; } #hour { background: url("images/hour.png") no-repeat center center; } #min { background: url("images/minute.png") no-repeat center center; } #second { background: url("images/second.png") no-repeat center center; }
注意:1小时时针旋转30度,1分钟分钟旋转6度,1秒钟秒钟旋转6度。
hour.style.transform = 'rotate(' + h * 30 + 'deg)';
min.style.transform = 'rotate(' + m * 6 + 'deg)';
second.style.transform = 'rotate(' + s * 6 + 'deg)';
2、定时执行:某一段程序需要在延迟多少时间后执行
设置定时器:【var timeid = window.setTimeout(“方法名或方法”, “延时”);】
清除定时器:【window.clearTimeout(timeid);】
示例
定时器
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



