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);
}