EN
JavaScript - 1 minute countdown timer
3
points
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
});
Ā