<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body><button id="stop">停止</button>
<script>
//需求:在控制台每隔一秒输出一次ok
var taskId = setInterval(function(){
console.log('ok')
},1000);
//先获取按钮元素对象,并绑定单机事件
document.getElementById("stop").onclick=function(){
//停止定时器的进程
clearInterval(taskId);
}
</script>
</body>
</html>
js定时器案例
![](https://img-home.csdnimg.cn/images/20240711042549.png)