16.JavaScript用setTimeout函数做出计时效果
JavaScript使用setTimeout函数做出计时效果:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="btn1">开始计时</button> <button id="btn2">结束计时</button> <div>0</div> <script> var num = 0; var timer = null; var div = document.querySelector("div"); var btn1 = document.querySelector("#btn1"); var btn2 = document.querySelector("#btn2"); btn1.onclick = function () { interval(function(){ num++; div.innerHTML = num; }, 1000); } //使用setTimeout函数实现定时器 function interval(callback, time) { timer = setTimeout(function(){ callback(); interval(callback, time);//重新调用interval(),异步执行 }, time); } btn2.onclick = function(){ clearTimeout(timer); } </script> </body> </html>