'Javascript/jQuery Countdown Timer with Update Capability

I’ve seen several examples for Javascript/jQuery countdown timers. I have implemented a 15 minute countdown timer based off the example at w3schools. However, I would like to add an update feature that allows me to add/subtract time to and from the clock. The timer starts at 15 minutes.

In my project the user will answers questions. After they answer the question and select submit, a time penalty or bonus is given. The penalty subtracts 3 seconds from the clock. The bonus adds 2 seconds to it. Below is an example of my code:

var mission_timer = 15;

function start_timer(){
        
        countDownDate  = new Date().getTime() + mission_timer * 60 * 1000;
        timer_interval = setInterval(function() {

            var now                   = new Date().getTime();
            var distance              = countDownDate - now;
            var minutes               = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var minutes_number_length = Number(String(minutes).length);
            var seconds               = Math.floor((distance % (1000 * 60)) / 1000);
            var seconds_number_length = Number(String(seconds).length);
            
            current_time = document.getElementById("game_timer").innerHTML = "TIME: " + minutes + ":" + seconds;
            update_timer = null;
            time_update  = 0;
            
            if (current_time === "TIME: 00:00") {
                $("#game_timer").css("color", "red");
                clearInterval(timer_interval);
                console.log("Time Expired");
            }else
            if (current_time === "TIME: 01:00") {
                $("#game_timer").css("color", "yellow");
                console.log("One Minute Left");
            }
        
        }, 1000);
    }




Solution 1:[1]

The counter works using countDownDate and now. You have to modify the countDownDate variable to add/substract time when user answers the questions.

//bonus for correct answer
countDownDate += 2 * 1000;

And

//penalty for wrong answer
countDownDate -= 3 * 1000;

Both of them have to be triggered by the Submit event of the question answered.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pablo Correa