The circular count down from 10 to 1 is working properly but I want to start the count down again (from 10 to 1 without reload) after a pause of 3 seconds. I have tried using a setTimeOut within a setTimeOut but it is not working. Here is the code.
var countdownNumberEl = document.getElementById('countdown-number');
var countdown = 10;
countdownNumberEl.textContent = countdown;
setInterval(function() {
countdown = --countdown <= 0 ? 10 : countdown;
countdownNumberEl.textContent = countdown;
setInterval(function(){
countdownNumberEl.textContent = countdown;
},3000)
}, 1000);
<div id="countdown">
<div id="countdown-number"></div>
<svg>
<circle r="18" cx="20" cy="20"></circle>
</svg>
</div>
CodePudding user response:
just add 3 sec as initial and change textContent when it will be less then 10
let countdownNumberEl = document.getElementById('countdown-number');
let countdown = 10;
countdownNumberEl.textContent = countdown;
setInterval(function() {
countdown = --countdown <= 0 ? 13 : countdown;
if (countdown > 10) {
return;
}
countdownNumberEl.textContent = countdown;
}, 1000);
<div id="countdown">
<div id="countdown-number"></div>
<svg>
<circle r="18" cx="20" cy="20"></circle>
</svg>
</div>
CodePudding user response:
I tried it with a pointer function. I stop the interval at reaching 1, and use setTimeout() to start a new interval.
startInterval = () => {
// setup markup and count
let countdownNumberEl = document.getElementById('countdown-number');
let countdown = 10;
countdownNumberEl.textContent = countdown;
// start the interval
intervalId = setInterval(function () {
--countdown;
if(countdown < 1) {
// stop interval
clearInterval(intervalId);
// pause and start a new interval
setTimeout(startInterval, 3000);
} else {
// update markup
countdownNumberEl.textContent = countdown;
}
}, 1000);
}
startInterval();
<div id="countdown">
<div id="countdown-number"></div>
<svg>
<circle r="18" cx="20" cy="20"></circle>
</svg>
</div>
ref: Javascript setInterval function to clear itself?
CodePudding user response:
Since you mentioned that you have tried to solve the problem with nested setTimeout functions. It is also possible to do that:
const countdownNumberEl = document.getElementById('countdown-number');
const repeatCountdownFrom = (n, waitTimeout) => {
countdownFrom(n, () =>
setTimeout(() =>
repeatCountdownFrom(n, waitTimeout)
, waitTimeout)
)
}
const countdownFrom = (n, callbackWhenDone) => {
if(n >= 0) {
setTimeout(() => {
countdownNumberEl.textContent = n;
countdownFrom(n - 1, callbackWhenDone);
}, 1000);
} else {
callbackWhenDone();
}
}
repeatCountdownFrom(10, 3000);
<div id="countdown-number"></div>