2_定时器.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <button id="btn">按钮A</button>
  11. <button id="btnB">按钮B</button>
  12. <button id="stop">停止</button>
  13. <button id="btnC">按钮C</button>
  14. <script>
  15. var btn = document.getElementById('btn')
  16. var btnB = document.getElementById('btnB')
  17. var stop = document.getElementById('stop')
  18. var btnC = document.getElementById('btnC')
  19. btn.onclick = function(){
  20. var a = 1
  21. var b = setTimeout(function(){
  22. a++
  23. console.log(a)
  24. },1000)
  25. }
  26. btnB.onclick = function(){
  27. var a = 1
  28. var c = setInterval(function(){
  29. a++
  30. console.log(a)
  31. },1000)
  32. stop.onclick = function(){
  33. clearInterval(c)
  34. }
  35. }
  36. //setTimeout 只执行一次
  37. //setInterval 不断的执行
  38. btnC.onclick = function(){
  39. //实现随机数 0-1
  40. var a = Math.random() * 100
  41. //Math.floor() 向下取整 跟四舍五入没有关系
  42. console.log(Math.floor(a))
  43. }
  44. </script>
  45. </body>
  46. </html>