Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Can I make this countdown work in only one function?

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)
    }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!