Languages
[Edit]
EN

JavaScript - 1 minute countdown timer

3 points
Created by:
May87
827

In this article, we would like to show you how to create a one-minute countdown timer in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let seconds = 60;

const makeIteration = () => {
    console.clear();
    if (seconds > 0) {
        console.log(seconds);
        seconds -= 1;
        setTimeout(makeIteration, 1000);  // 1 second waiting
    } else {
        console.log('Done!');
    }
};

setTimeout(makeIteration, 1000);  // 1 second waiting

Ā 

Reusable solutions

1. setTimeout() functionĀ basedĀ solution

In the below example, we use setTimeout() function to schedule anĀ iteration execution always when 1 second occurred, breaking counting when 60th iteration occurred.

// ONLINE-RUNNER:browser;

const runTimer = (callback) => {
    let handle = null;
	let seconds = 60;
    const makeIteration = () => {
        if (seconds > 0) {
            seconds -= 1;
            callback(seconds);
            handle = setTimeout(makeIteration, 1000);  // 1 second waiting
        } else {
            callback(0);
        }
    };
  	callback(seconds);
    handle = setTimeout(makeIteration, 1000);  // 1 second waiting
    return () => clearTimeout(handle);
};


// Usage example:

runTimer((seconds) => {
    console.clear();
    console.log(seconds || 'Done!');  // seconds variable value equals to 0 means counting done
});

Ā 

2. setInterval() functionĀ basedĀ solution

In the below example, we use setInterval() function to execute anĀ iteration once per 1 second, breaking counting when 60th iteration occurred.

// ONLINE-RUNNER:browser;

const runTimer = (callback) => {
    let handle = null;
	let seconds = 60;
    const makeIteration = () => {
        if (seconds > 0) {
            seconds -= 1;
            callback(seconds);
        } else {
            callback(0);
            clearInterval(handle);
        }
    };
  	callback(seconds);
    handle = setInterval(makeIteration, 1000);  // 1 second waiting
    return () => clearInterval(handle);
};


// Usage example:

runTimer((seconds) => {
    console.clear();
    console.log(seconds || 'Done!');  // seconds variable value equals to 0 means counting done
});

Ā 

See also

  1. Dirask Snippets -Ā js for loop with settimeout() example

References

  1. setTimeout() - Web APIs | MDN

Alternative titles

  1. JavaScript - one minute countdown timer
  2. JavaScript - 60 seconds countdown timer
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join