|
|
|
|
|
|
|
|
|
|
|
--- |
|
|
|
|
|
example: |
|
|
|
|
|
title: Timer Button |
|
|
|
|
|
instructions: > |
|
|
|
|
|
Create a function called `updateTimer()` containing the timer updating logic. |
|
|
|
|
|
Then use `setInterval(updateTimer, 1000)` to update the timer every second |
|
|
|
|
|
when the user clicks **Start**. |
|
|
|
|
|
hint: > |
|
|
|
|
|
Store the timer id in the button node and use `clearInterval()` to stop the timer |
|
|
|
|
|
when the user clicks **Stop**. |
|
|
|
|
|
initial: |
|
|
|
|
|
js: |+2 |
|
|
|
|
|
const timerBtn = document.getElementById('timer-button') |
|
|
|
|
|
|
|
|
|
|
|
timerBtn.addEventListener('click', ev => { |
|
|
|
|
|
const btn = ev.currentTarget |
|
|
|
|
|
const action = btn.value |
|
|
|
|
|
console.log(action) |
|
|
|
|
|
|
|
|
|
|
|
if (action === 'start') { |
|
|
|
|
|
btn.value = 'stop' |
|
|
|
|
|
btn.textContent = 'Stop Timer' |
|
|
|
|
|
} else if (action === 'stop') { |
|
|
|
|
|
btn.value = 'start' |
|
|
|
|
|
btn.textContent = 'Start Timer' |
|
|
|
|
|
} |
|
|
|
|
|
}) |
|
|
|
|
|
solution: |
|
|
|
|
|
js: |+2 |
|
|
|
|
|
const timerBtn = document.getElementById('timer-button') |
|
|
|
|
|
|
|
|
|
|
|
const updateTimer = () => { |
|
|
|
|
|
const then = timerBtn.startTime |
|
|
|
|
|
const now = new Date() |
|
|
|
|
|
let seconds = Math.floor((now - then) / 1000) |
|
|
|
|
|
|
|
|
|
|
|
let minutes = 0 |
|
|
|
|
|
if (seconds >= 60) { |
|
|
|
|
|
minutes = Math.floor(seconds / 60) |
|
|
|
|
|
seconds = seconds - minutes * 60 |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
minutes = (minutes < 10 ? '0' : '') + minutes |
|
|
|
|
|
seconds = (seconds < 10 ? '0' : '') + seconds |
|
|
|
|
|
|
|
|
|
|
|
document.getElementById('timer-minutes').textContent = minutes |
|
|
|
|
|
document.getElementById('timer-seconds').textContent = seconds |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
timerBtn.addEventListener('click', ev => { |
|
|
|
|
|
const btn = ev.currentTarget |
|
|
|
|
|
const action = btn.value |
|
|
|
|
|
|
|
|
|
|
|
if (action === 'start') { |
|
|
|
|
|
btn.value = 'stop' |
|
|
|
|
|
btn.textContent = 'Stop Timer' |
|
|
|
|
|
btn.startTime = new Date() |
|
|
|
|
|
btn.timerId = setInterval(updateTimer, 1000) |
|
|
|
|
|
} else if (action === 'stop') { |
|
|
|
|
|
btn.value = 'start' |
|
|
|
|
|
btn.textContent = 'Start Timer' |
|
|
|
|
|
clearInterval(btn.timerId) |
|
|
|
|
|
} |
|
|
|
|
|
}) |
|
|
|
|
|
css: ~ |
|
|
|
|
|
output: js4shiny::html_document_plain |
|
|
|
|
|
|
|
|
|
|
|
--- |
|
|
|
|
|
|
|
|
|
|
|
<div class="controls"> |
|
|
|
|
|
<button id="timer-button" value="start">Start Timer</button> |
|
|
|
|
|
</div> |
|
|
|
|
|
|
|
|
|
|
|
<div id="timer"> |
|
|
|
|
|
<span id="timer-minutes">00</span>:<span id="timer-seconds">00</span> |
|
|
|
|
|
</div> |