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:
xxxxxxxxxx
1
let seconds = 60;
2
3
const makeIteration = () => {
4
console.clear();
5
if (seconds > 0) {
6
console.log(seconds);
7
seconds -= 1;
8
setTimeout(makeIteration, 1000); // 1 second waiting
9
} else {
10
console.log('Done!');
11
}
12
};
13
14
setTimeout(makeIteration, 1000); // 1 second waiting
In the below example, we use setTimeout()
function to schedule an iteration execution always when 1 second occurred, breaking counting when 60th iteration occurred.
xxxxxxxxxx
1
const runTimer = (callback) => {
2
let handle = null;
3
let seconds = 60;
4
const makeIteration = () => {
5
if (seconds > 0) {
6
seconds -= 1;
7
callback(seconds);
8
handle = setTimeout(makeIteration, 1000); // 1 second waiting
9
} else {
10
callback(0);
11
}
12
};
13
callback(seconds);
14
handle = setTimeout(makeIteration, 1000); // 1 second waiting
15
return () => clearTimeout(handle);
16
};
17
18
19
// Usage example:
20
21
runTimer((seconds) => {
22
console.clear();
23
console.log(seconds || 'Done!'); // seconds variable value equals to 0 means counting done
24
});
In the below example, we use setInterval()
function to execute an iteration once per 1 second, breaking counting when 60th iteration occurred.
xxxxxxxxxx
1
const runTimer = (callback) => {
2
let handle = null;
3
let seconds = 60;
4
const makeIteration = () => {
5
if (seconds > 0) {
6
seconds -= 1;
7
callback(seconds);
8
} else {
9
callback(0);
10
clearInterval(handle);
11
}
12
};
13
callback(seconds);
14
handle = setInterval(makeIteration, 1000); // 1 second waiting
15
return () => clearInterval(handle);
16
};
17
18
19
// Usage example:
20
21
runTimer((seconds) => {
22
console.clear();
23
console.log(seconds || 'Done!'); // seconds variable value equals to 0 means counting done
24
});