<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="begain">开启定时器</button>
<button class="stop">停止定时器</button>
<script>
var begain = document.querySelector('.begain');
var stop = document.querySelector('.stop');
var timer = null; //全局变量 null是个空对象 ;设置var timer; 会返回undefined
begain.addEventListener('click', function() {
timer = setInterval(function() {
console.log('nihaoma');
}, 1000);
})
stop.addEventListener('click', function() {
clearInterval(timer);
})
</script>
</body>
</html>
06-28
7399
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-10
12-12
05-22
231
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交