Hey folks! I’m trying to create a simple timer using JavaScript but I’m hitting a wall. I’ve got two buttons (Start and Stop) and a div that should show the seconds ticking up. When I click Start though nothing happens. Can anyone spot what I’m doing wrong? Here’s my code:
let timer = 0;
function startTimer() {
setInterval(() => {
document.querySelector('#timer-display').textContent = ++timer;
}, 1000);
}
<div id="timer-display">0</div>
<button onclick="startTimer()">Start</button>
<button>Stop</button>
I thought this would work but the timer stays at 0. Any ideas?
I see the issue. Your code’s structure is correct, but you’re not handling multiple clicks on the Start button. Each click creates a new interval without clearing the previous ones, leading to overlapping timers. To fix this, declare ‘intervalId’ outside the function and clear any existing interval before starting a new one:
let timer = 0;
let intervalId;
function startTimer() {
clearInterval(intervalId);
intervalId = setInterval(() => {
document.querySelector('#timer-display').textContent = ++timer;
}, 1000);
}
This ensures only one timer runs at a time. Don’t forget to implement the Stop functionality as well.
hey claire, looks like ur missing a clearInterval for the stop button. also, u might wanna store the interval ID returned by setInterval so u can clear it later. somethin like:
let intervalId;
function startTimer() {
intervalId = setInterval(() => {…}, 1000);
}
function stopTimer() {
clearInterval(intervalId);
}
I’ve encountered this issue before, and it can be frustrating. One thing to consider is browser behavior with inactive tabs. Some browsers throttle JavaScript in background tabs to conserve resources. This means your timer might not run as expected if the tab isn’t active.
To mitigate this, you could use Date.now()
to calculate elapsed time instead of relying on interval accuracy. Here’s a rough idea:
let startTime;
let intervalId;
function startTimer() {
startTime = Date.now();
intervalId = setInterval(() => {
const elapsed = Math.floor((Date.now() - startTime) / 1000);
document.querySelector('#timer-display').textContent = elapsed;
}, 100);
}
This approach updates more frequently and calculates the actual elapsed time, which can be more reliable across different browser states. Remember to implement a stop function that clears the interval as well.