停止setlnterval()定时器
clearInterval ()方法取消了先前通过调用setInterval ()建立的定时器。
注:
1.window可以省略
2.里面的参数就是定时器的标识符
示例代码:
<!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="begin">开启定时器</button> <button class="stop">停止定时器</button> </body> <script> var begin = document.querySelector('.begin') var stop = document.querySelector('.stop') // hello null是一个空对象 var hello = null; begin.addEventListener('click', function () { // hello 是局部变量 hello = setInterval(function () { console.log("你好"); }, 1000) }) stop.addEventListener('click', function () { clearInterval(hello) }) </script> </html>