Reputation: 21
This code works fine (It is a countdown for a project I'm doing), but i want to do it with only one function. It is possible?
function workingCountdown(){
//Set an interval that call the countdown function every second
window.variableCountdown = setInterval(countdown, 1000)
}
function countdown(){
//CHECK IF SECONDS IS BIGGER THAN ONE
if(seconds>1){
//IF YES
//Substract 1 to the seconds variable
window.seconds--
//Change the countdown text according to seconds left
document.getElementById("countdown").innerHTML = "You have " + seconds + " seconds left"
} else {
//IF NO
//Notify the user that they ran out of time by changing the countdown text
document.getElementById("countdown").innerHTML = "You have 0 seconds left"
//Let pass fifty miliseconds so the countdown text can change before the alert is played
setTimeout(function(){cpsTestFinish()}, 50)
//Stop the countdown repeat
clearInterval(variableCountdown)
}
}
Upvotes: 2
Views: 115
Reputation: 63550
Initialise the counter in the main function. If it reaches zero call the other function, otherwise log the count, and call the function again passing in the reduced count.
const countdown = document.querySelector('#countdown');
function fn() {
countdown.innerHTML = `You ran out of time!`;
}
function timer(seconds = 5) {
if (seconds === 0) {
fn();
} else {
countdown.innerHTML = `You have ${seconds} seconds left`;
setTimeout(timer, 1000, --seconds);
}
}
timer();
<div id="countdown"></div>
Upvotes: 1
Reputation: 2250
What about something like this:
function countdown(remaining) {
if(remaining > 0) {
// update the remaining time UI
console.log(`Remaining ${remaining}`);
setTimeout(() => countdown(remaining - 1), 1000)
} else {
// do whatever you need to do when the countdown is over
console.log("DONE");
}
}
// then you call
countdown(10)
This also displays a "Remaining" at the very start so the user is notified with the actual starting seconds.
Also you don't need to keep any reference to the interval or window
variables.
Upvotes: 0