无限循环中的计时事件 - 带有停止按钮

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <button onClick="myTimer = setInterval(myCounter, 1000)">启动计数器</button>
  6.  
  7. <p id="demo">点击上面的按钮,我会永远计数。</p>
  8.  
  9. <button onClick="clearInterval(myTimer)">停止计数器</button>
  10.  
  11. <script>
  12. var c = 0;
  13. function myCounter() {
  14. document.getElementById("demo").innerHTML = ++c;
  15. }
  16. </script>
  17.  
  18. </body>
  19. </html>