js计时器方法的使用

时间:2023-03-09 20:17:12
js计时器方法的使用

js中计时器重要使用window.setInterval()方法和window.setTimeout()方法,

其中setInterval()方法的作用是每隔一段时间执行一次方法,而window.setTimeout()在一段时间内调用函数。

setTimeout()方法一般通过调用自身迭代的方式实现计时器。与这两个方法对应的,还有清除这两个函数效果的

两个方法,分别是window.clearInterval()和window.clearTimeout()。

1.setInterval()和clearInterval()  (window可以省略)

(1)setInterval()方法常用的语法如下:

setInterval(function,interval);

其中function是将要在间隔时间内执行的函数,interval是间隔的时间,单位是毫秒。

(2)clearInterval()方法的常用语法如下:

timer = setInterval(function,interval);

clearInterval(timer);

例子:

 <html>
<head></head>
<body>
<p id="timer">点击开始计时!</p>
<div>
<button id="cutTimer" onclick="start()">开始</button>
<button id="cutTimer" onclick="stop()">停止</button>
</div>
<script>
var cutT = document.getElementById("cutTimer"); var timer1 = null; function start(){
var countTime = function(){
date = new Date();
dateStr = date.toLocaleTimeString();
document.getElementById("timer").innerHTML = dateStr;
} timer1 = window.setInterval(countTime,1000); } function stop(){
console.log("timer stop:"+timer1);
window.clearInterval(timer1);
}; </script>
</body>
</html>

在这个例子中,点击开始后(会有一段延迟),页面上每隔1000毫秒(也就是1秒)执行一次,也就是显示当前的时分秒。

2.setTimeout()和clearTimeout()

这两个方法与setInterval()和clearInterval()方法用法类似,示例如下:

 <html>
<head></head>
<body>
<p id="timer"></p>
<div>
<button id="cutTimer" onclick="timeOutAlert();">执行</button>
<button id="cutTimer" onclick="stopTimeOutAlert();">停止</button>
</div>
<script>
timeOut = null;
function timeOutAlert(){
timeOut = window.setTimeout(function(){
console.log("time out..."+timeOut);
timeOutAlert();
},1000);
} function stopTimeOutAlert(){
console.log("timeCut:"+timeOut);
window.clearTimeout(timeOut);
}
</script>
</body>
</html>

可以看到timeOutAlert()方法每隔1000毫秒调用自身,在控制台打印出当前timeOut的值,timeOut第一次使用

setTimeout()后为1,每次增加1,clearTimeout()通过这个数字作为入参清除当前的setTimeout()。