setinterval你們都很瞭解,可是若是時間長的話,偏差也會愈來愈大,因此我習慣上使用settimeout的遞歸,閒來沒事,寫了一個定時器的遞歸css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> </head> <body> <div> </div> <button>點擊</button> </body> <script> $(function () { var num = 0; var end = ""; $("button").on("click", function () { function result() { end = setTimeout(function() { num++; $("div").text(num); result() }, 1000); } result(); }) }) </script> </html>
嗯,,看似很完美,有一個很明顯的bug,那就是在頁面上,越點擊,,它跑的越快,並無依照1000毫秒的時間進行間隔執行,這是由於,,每點擊一次,,settimeout就註冊一次,因此會愈來愈快,,解決的思路就是每次點擊的時候進行定時器的清除,,代碼以下:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> </head> <body> <div> </div> <button>點擊</button> </body> <script> $(function () { var num = 0; var end = ""; $("button").on("click", function () { clearTimeout(end); function result() { end = setTimeout(function() { num++; $("div").text(num); result() }, 1000); } result(); }) }) </script> </html>
嗯,,完美jquery