Search code examples
javascriptcountdowntimer

CodeHS JavaScript Timer- Countdown


I work on CodeHS and need to make a countdown timer for my powerups in the game I'm making, Breakout. I need the timer to be reusable so no for loops, it needs to go down in seconds/milliseconds (it doesn't matter which) and preferably last 30 seconds or 30,000 milliseconds. Remember this is CodeHS I'm working on.


Solution

  • If you want something to happen 30 seconds after you start your timer you could do something like this:

    //set the time remaining to 30 outside of a function so it is global
    var timeRemaining = 30;
    
    function start(){
    //set the timer to run the function countdown once every second(1000 milliseconds)
        setTimer(countdown, 1000)
    }
    
    function countdown(){
        /*every time it is called this function subtracts one from the time if it is
        more than 30, when it reaches 0 stops the timer and resets the time*/
        if(timeRemaining<=0){
            stopTimer(countdown);
            timeRemaining = 30;
            println("Done");
            //30 seconds has passed, do what you need here(call your function)
        }else{
            timeRemaining--;
            println(timeRemaining+" seconds left")
        }
    }
    

    Add your function or whatever you want to happen after the time is up whereprintln("Done") is.

    Because timeRemaining is set back to 30 at the end, you can reuse the timer by calling setTimer(countdown, 1000) again.

    You can remove the println statments, they are just to see what is happening.

    If CodeHS doesn't want hardcoded numbers (I think they call them "magic numbers"), replace the 30s with a constant set to 30.

    Let me know if you need a better explanation.