Problem with reset function in counter project

Hello everybody,

I’m new here and my name is Hans. For Javascript I have a question about the following code.

"use strict";

const startBtn = document.getElementById("btn-start");
const resetBtn = document.getElementById("btn-reset");
const countDisplay = document.getElementById("time-left");
let timeLeft = 10;

startBtn.addEventListener("click", CountDown);

function CountDown() {
    timeLeft = timeLeft - 1;
    if (timeLeft <= 0) {
        clearTimeout(timeLeft = 0);
    }
    setTimeout( CountDown, 1000);
    countDisplay.innerHTML = timeLeft;
}

resetBtn.addEventListener("click", resetCounter);

function resetCounter() {
    let timeZero = 10;
    countDisplay.innerHTML = timeZero;
}

It is a counter that works so far. This counts down from 10 to 0. Unfortunately, the reset function (function resetCounter) doesn’t work and I can’t find the error.

Can someone give me a tip here.

Best regards
Hans

In the resetCounter function you declare a new variable which isn’t used in your CountDown function.
The second time you click the startBtn the variable timeLeft is still 0.
And the function CountDown is essentially an infinite loop. SetTimeout keeps running even after timeLeft = 0;

Your code has both a syntax error and logic errors.

clearTimeout(timeLeft = 0);

This is the syntax error. I recommend that you google and read the correct syntax.

The logic errors are as hinted by @exari.

Hi exari,

thanks for the answer. I’ve learned a lot again and will try to change the code.

Best regards
Hans

Hi gaac510,

thank you for pointing out the syntax error. I’m trying to change that.

Best regards
Hans

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.