您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

77 行
2.2KB

  1. ---
  2. example:
  3. title: Timer Button
  4. instructions: >
  5. Create a function called `updateTimer()` containing the timer updating logic.
  6. Then use `setInterval(updateTimer, 1000)` to update the timer every second
  7. when the user clicks **Start**.
  8. hint: >
  9. Store the timer id in the button node and use `clearInterval()` to stop the timer
  10. when the user clicks **Stop**.
  11. initial:
  12. js: |+2
  13. const timerBtn = document.getElementById('timer-button')
  14. timerBtn.addEventListener('click', ev => {
  15. const btn = ev.currentTarget
  16. const action = btn.value
  17. console.log(action)
  18. if (action === 'start') {
  19. btn.value = 'stop'
  20. btn.textContent = 'Stop Timer'
  21. } else if (action === 'stop') {
  22. btn.value = 'start'
  23. btn.textContent = 'Start Timer'
  24. }
  25. })
  26. solution:
  27. js: |+2
  28. const timerBtn = document.getElementById('timer-button')
  29. const updateTimer = () => {
  30. const then = timerBtn.startTime
  31. const now = new Date()
  32. let seconds = Math.floor((now - then) / 1000)
  33. let minutes = 0
  34. if (seconds >= 60) {
  35. minutes = Math.floor(seconds / 60)
  36. seconds = seconds - minutes * 60
  37. }
  38. minutes = (minutes < 10 ? '0' : '') + minutes
  39. seconds = (seconds < 10 ? '0' : '') + seconds
  40. document.getElementById('timer-minutes').textContent = minutes
  41. document.getElementById('timer-seconds').textContent = seconds
  42. }
  43. timerBtn.addEventListener('click', ev => {
  44. const btn = ev.currentTarget
  45. const action = btn.value
  46. if (action === 'start') {
  47. btn.value = 'stop'
  48. btn.textContent = 'Stop Timer'
  49. btn.startTime = new Date()
  50. btn.timerId = setInterval(updateTimer, 1000)
  51. } else if (action === 'stop') {
  52. btn.value = 'start'
  53. btn.textContent = 'Start Timer'
  54. clearInterval(btn.timerId)
  55. }
  56. })
  57. css: ~
  58. output: js4shiny::html_document_plain
  59. ---
  60. <div class="controls">
  61. <button id="timer-button" value="start">Start Timer</button>
  62. </div>
  63. <div id="timer">
  64. <span id="timer-minutes">00</span>:<span id="timer-seconds">00</span>
  65. </div>