定时器
暂停、继续和重置
引用地址:https://blog.csdn.net/djzhao627/article/details/108431803
一个秒级别计数器:点击“开始"按钮从0开始每隔1秒计数,点击"停止"按钮停止计数。计数停止后,再次点击"开始"按钮继续计数。
<button onclick="myCounter.startCount()">开始</button>
<input id="counter" type="text" readonly="readonly">
<button onclick="myCounter.stopCount()">停止</button>
<button onclick="myCounter.resetCount()">重置</button>
<script>
var myCounter = (function () {
var step = 0;
var intervalId = null;
function count() {
document.getElementById("counter").value = step;
step = step + 1;
}
function start() {
if (intervalId == null) {
count();
intervalId = setInterval(count, 1000);
}
}
function stop() {
clearInterval(intervalId);
intervalId = null;
}
function reset() {
stop();
step = 0;
document.getElementById("counter").value = "";
}
return { startCount: start, stopCount: stop, resetCount: reset }
})()
</script>
优秀文章:
清除定时器
引用地址:https://blog.csdn.net/ycx60rzvvbj/article/details/113256013
清除指定定时器
在创建定时器(setInterval)的时候用一个变量保存它,直接清除clearInterval
let timer = setInterval(function () {
console.log('timer');
}, 1000);
clearInterval(timer);
清除所有定时器
方法一:
let end = setInterval(function () { }, 10000);
for (let i = 1; i <= end; i++) {
clearInterval(i);
}
方法二:
let id = setTimeout(() => { }, 0);
while(id > 0){
window.clearTimeout(id)
id --;
}