2_定时器.html 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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">按钮</button>
  11. <button id="stop">按钮B</button>
  12. <button id="num">按钮C</button>
  13. <script>
  14. var btn = document.getElementById('btn')
  15. var stop = document.getElementById('stop')
  16. var num = document.getElementById('num')
  17. /* 间隔多少毫秒去执行 */
  18. btn.onclick = function () {
  19. var b = 1
  20. var a = setInterval(function () {
  21. if (b < 10) {
  22. b++
  23. console.log(b)
  24. } else {
  25. clearInterval(a)
  26. }
  27. }, 1000)
  28. }
  29. stop.onclick = function () {
  30. var c = setTimeout(function () {
  31. console.log(111)
  32. }, 1000)
  33. }
  34. /*
  35. setInterval 不断的去执行 通过clearInterval 清除定时器
  36. setTimeout 只执行一次 */
  37. num.onclick = function () {
  38. //获取一个随机数
  39. //Math.random() 0~1
  40. //Math.floor 向下取整 跟四舍五入没关系
  41. var h = setInterval(function () {
  42. var nn = Math.random() * 10
  43. var mm = Math.floor(nn)
  44. console.log(mm)
  45. }, 1000)
  46. }
  47. </script>
  48. </body>
  49. </html>