I'm trying to build a timer that when it reaches zero it stops. I've tried to make it with a clearInterval but it is not working. As it does nothing.
function startGame() {
var minute = 00;
var sec = 10;
const timeInterval = setInterval(function() {
document.getElementById("gameTimer").innerHTML =
minute + " : " + sec;
sec--;
if (sec == 00) {
minute--;
sec = 59;
if (minute == 00) {
minute = 0;
clearInterval(timeInterval)
}
} else if (minute == 0 && sec == 1) {
document.getElementById("finishGame").innerHTML = "hello"
}
}, 1000);
};
<span id="gameTimer"></span>
<button onClick="startGame()">Start Counter</button>
<span id="finishGame"></span>
You need to use minute <= 0 condition, since you subtract one from minute first, and then check for minute == 0, which will be false, since minute will be -1.
Also, its better to put all if conditions first, then subtract one from second.
function startGame() {
var minute = 0;
var sec = 10;
const timeInterval = setInterval(function() {
document.getElementById("gameTimer").innerHTML = minute + " : " + sec;
if (sec <= 0) {
minute--;
sec = 59;
if (minute <= 0) {
minute = 0;
clearInterval(timeInterval)
}
} else if (minute == 0 && sec == 1) {
document.getElementById("finishGame").innerHTML = "hello";
}
sec--;
}, 1000);
};
<body>
<span id="gameTimer"></span>
<button onClick="startGame()">Start Counter</button>
<span id="finishGame"></span>
</body>
Related
I have taken this simple timer method from here.
What I want is pretty simple, yet I can’t figure it out.
When the timer reaches zero (0:00), I want a popup alert. At the same time, the timer should continue in negative time.
So everything is working, except the popup. Any idea why?
window.onload = function() {
var minute = 0;
var sec = 3;
setInterval(function() {
document.getElementById("timer").innerHTML = minute + " : " + sec;
sec--;
if (sec == 00) {
minute --;
sec = 59;
if (minute == 0 && sec == 00) {
alert("You failed!");
}
}
}, 1000);
}
<div class="countdown" class="failed" id="coutdown">
Time remaining to find solution: <span id="timer">10 : 00</span>
</div>
window.onload = function() {
var minute = 0;
var sec = 3;
var timer = document.getElementById("timer");
setInterval(function() {
if (sec === 0) {
timer.innerHTML = minute + " : " + sec;
if (minute === 0 && sec === 0) {
alert("You failed!");
}
minute--;
sec = 60;
} else {
timer.innerHTML = minute + " : " + sec;
}
sec--;
}, 1000);
}
<div class="countdown" class="failed" id="coutdown">
Time remaining to find solution: <span id="timer">10 : 00</span>
</div>
You are checking minute and second conditions after minute-- in your code, which means -1 is not equal to zero. Write an if condition before making minus 1 in your code.
Please use console.log("You failed!") instead of alert("You failed!") to ensure an accurate result.
Your conditional is checking whether sec == 0 immediately after you set sec = 59, so the conditional will never occur. Do you mean to have the order of this setter and the conditional swapped?
This is what I mean by restructuring the code entirely into reusable functions. comment what you don't understand and I will explain. I try not to hard code anything timer fetches its starter value from HTML.
const display = document.getElementById("timer");
function toArray(domEl){
return domEl.innerHTML.split(':').map(el => +el);
}
function getSec(timeArr){
if(timeArr.length > 3 || timeArr.length === 0) return;
return timeArr.reverse().map((el, i) => el * 60 ** i).reduce((cur,accu)=> cur + accu);
}
let totalSec = getSec(toArray(display))
setInterval(()=>{
totalSec--;
display.textContent = formatTime(totalSec);
},1000)
function formatTime(sec){
const time = {hr:0, min:0, sec:0};
time.hr = ~~(sec/3600) || 0;
time.min = ~~(~~(sec%3600)/60);
time.sec = ~~(sec%3600)%60;
if(time.hr===0 && time.min===0 && time.sec ===0) alert("You Faild!")
return `${time.hr ? time.hr + ':':''}${padTime(time.min)}:${padTime(time.sec)}`
}
function padTime(time){
return time? String(time).padStart(2,0):0;
}
<div class="countdown" class="failed" id="coutdown">
Time remaining to find solution: <span id="timer">0:01:05</span>
</div>
I have a timer that counts down from 5:00 minutes, but it does not stop! It just goes into the negative.
HTML
<p>Click the button to begin the quiz. Good Luck!</p>
<button id="start" class="button">Start</button>
<div class="timer">
Timer: <span id="time"> 5:00 </span> minutes
</div>
JavaScript
document.getElementById('time').innerHTML = 05 + ":" + 00;
function startTimer() {
var p_time = document.getElementById('time').innerHTML;
var timeArray = p_time.split(/[:]+/);
var min = timeArray[0];
var sec = checkSecond((timeArray[1]-1));
if(sec==59){min=min-1}
if(min <= 0 && sec == 0) {alert("Time is up!")}
document.getElementById('time').innerHTML = min + ":" + sec;
setTimeout(startTimer, 1000);
}
function checkSecond(seconds) {
if(seconds <10 && seconds >= 0) {seconds ="0" + seconds};
if(seconds <0) {seconds = "59"};
return seconds;
}
CSS
.timer {
color: var(--primary);
font-size: 16px;
font-weight: bold;
margin: 10px;
}
I have the JS saying that when minutes is less than or equal to 0 AND seconds equal 0, then alert "time is up". So I get the popup alert, but once I click "ok" on the popup, the timer keeps counting down into negative.
Also, in the picture, the "5:00" isn't showing up - it only shows one zero.
You have to tell it to stop. E.g. by returning if the time is up. Something like
if(min <= 0 && sec == 0) {return alert("Time is up!")}
// ^ now the next statements won't run
document.getElementById('time').innerHTML = min + ":" + sec;
setTimeout(startTimer, 1000);
you need to remove the timer by using clearTimeout once the timer completes 5 minutes.
check this if stackoverflow snippets isn't working - https://jsfiddle.net/e5v80xmk/
document.getElementById('time').innerHTML = 05 + ":" + 00;
document.getElementById('start').addEventListener('click', startTimer);
var timerRef = null;
function startTimer() {
var p_time = document.getElementById('time').innerHTML;
var timeArray = p_time.split(/[:]+/);
var min = timeArray[0];
var sec = checkSecond((timeArray[1] - 1));
if (sec == 59) {
min = min - 1
}
document.getElementById('time').innerHTML = min + ":" + sec;
if (min <= 0 && sec == 0) {
clearTimeout(timerRef)
alert("Time is up!")
return
}
timerRef = setTimeout(startTimer, 1000);
}
function checkSecond(seconds) {
if (seconds < 10 && seconds >= 0) {
seconds = "0" + seconds
};
if (seconds < 0) {
seconds = "59"
};
return seconds;
}
<p>Click the button to begin the quiz. Good Luck!</p>
<button id="start" class="button">Start</button>
<div class="timer">
Timer: <span id="time"> 5:00 </span> minutes
</div>
I'm creating a countdown timer in minutes and seconds that that displays on the page - all seems to work fine with the bit of code I have. The only issue is when the alert box pops up I want the clock to stop counting down also.
I thought that including the return keyword under the alert pop up would resolve the issue but the clock keep ticking down.
Below is the code. Any help would be great.
window.onload = function() {
var hour = 1;
var sec = 59;
setInterval(function() {
document.getElementById("timer").innerHTML = hour + " : " + sec;
sec--;
if (sec == 0) {
hour--;
sec = 59;
}
if (hour == 1 && sec == 51)
{
alert("Stop, you have not completed the task in the alotted time");
return;
}
}, 1000);
}
To do that you need to save that Interval in a variable and then deactivate the interval with clearInterval. So your code would be like this:
window.onload = function() {
var hour = 1;
var sec = 59;
let counting_interval = setInterval(function() {
document.getElementById("timer").innerHTML = hour + " : " + sec;
sec--;
if (sec == 0) {
hour--;
sec = 59;
}
if (hour == 1 && sec == 51)
{
alert("Stop, you have not completed the task in the alotted time");
clearInterval(counting_interval); // pass the interval as the argument and it will stop to call the interval anymore
return;
}
}, 1000);
}
You need to set a timeout, not an interval. Intervals trigger until they're stopped. Timeouts happen once.
const interval = setInterval( function() {
document.getElementById("timer").innerHTML = hour + " : " + sec;
sec--;
if (sec == 0) {
hour--;
sec = 59;
}
});
const timeoutPeriod = 2 * 60 * 60 * 1000;
setTimeout(
function(){
clearInterval(interval);
alert("Stop, you have not completed the task in the alotted time");
}, timeoutPeriod
);
this is my code, it doesn't work I think the problem is what I'm returning in the function.
Please, help.
var minutes = 25;
var seconds = 60;
function myFunction() {
var start = setInterval(function() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0) {
seconds = 60;
minutes--;
}
if (seconds == 0 && minutes == 0) {
alert("done");
}
var time = minutes + ":" + seconds;
return time;
}, 1000);
return start;
}
console.log(myFunction());
Description
Minor changes to show your code is working
Bugs?
- Requires a minutes and seconds variable be declared before myFunction is called, the rewrite takes these are parameters.
- Doesn't check if the variables are negative and thereby expects "valid" data from the user.
- Only allows for console.log(time), the rewrite allows a function to be passed in for each tick and onTimerComplete
var minutes = 25;
var seconds = 60;
function myFunction() {
var start = setInterval(function() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0 && minutes == 0) {
alert("done");
// added this to clear the timer on 0 minutes 0 seconds
clearInterval(start);
return;
}
if (seconds == 0) {
seconds = 59;
minutes--;
}
var time = minutes + ":" + seconds;
// adding this as this is the function being repeated
console.log(time);
}, 1000);
}
myFunction();
How I would rewrite this
function timer(minutes, seconds, onTimerChanged, onTimerComplete) {
var timerPointer = undefined;
// if minutes is below 0 reset to 0
if (minutes < 0) {
minutes = 0;
}
// if seconds is set below 0 reset to 0
if (seconds < 0) {
seconds = 0;
} else if (seconds > 59) {
// this will add to minutes if too many seconds are passed
minutes += Math.floor(seconds / 60);
seconds = seconds % 60;
}
// this is the function to be called on each tick call
// default: console.log
if (onTimerChanged === undefined) {
onTimerChanged = console.log;
}
if (onTimerComplete === undefined) {
onTimerComplete = function() {
console.log("done")
};
}
// starts the timer
this.start = function() {
timerPointer = setInterval(tick, 1000);
}
// stops the timer
this.stop = clearInterval(timerPointer);
this.time = undefined;
// function for each tick
function tick() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0 && minutes == 0) {
// added this to clear the timer on 0 minutes 0 seconds
clearInterval(timerPointer);
if (onTimerComplete) {
onTimerComplete();
}
return;
}
if (seconds == 0) {
seconds = 59;
minutes--;
}
// pads the numbers so they are always two digits
this.time = padToTwo(minutes) + ":" + padToTwo(seconds);
// if onTimeChanged exists call it
if (onTimerChanged) {
onTimerChanged(this.time);
}
}
// padding the string to be two digits always
function padToTwo(number) {
if (number <= 99) {
number = ("0" + number).slice(-2);
}
return number;
}
}
// create the timer object
var test = new timer(-1, 500);
// start the timer
test.start();
// this would also work
// new timer(minutes, seconds).start();
Both of the returns you have are pointless. console.log() will only output one time. You have to have console.log() inside of the setInterval() function to run multiple times. You should also clear the interval to avoid any memory leaks.
Last, I also added in minutes > 0 because otherwise seconds would be 60 and minutes would be -1 when time has run out.
var minutes = 25;
var seconds = 60;
function myFunction() {
var start = setInterval(function() {
if (seconds > 0) {
seconds--;
}
if (seconds == 0 && minutes > 0) {
seconds = 60;
minutes--;
} else
if (seconds == 0 && minutes == 0) {
clearInterval(start);
alert("done");
}
var time = minutes + ":" + seconds;
console.log(time);
}, 1000);
}
myFunction();
Your code (almost) works. You just will have to wait 26 minutes to see the alert.
if (seconds == 0 && minutes == 0) {
clearInterval(start);
alert("done");
}
I found a sample JavaScript count up timer that meets my needs, including a start/pause and reset function. However it's missing one thing that I need it to do; have the script add 2 seconds to the display timer when a button is selected.
Here is my HTML:
<!doctype html>
<html>
<head>
<title></title>
</head>
<p><span id="my_timer" style="color: #f00; font-size: 2000%; font-weight: bold;">00:00:00</span></p>
<button id="control" onclick="changeState();">START</button>
<button id="reset" onClick="reset();">RESET</button>
<button id="updateClock" onClick="updateClock();">2 SECONDS</button>
<script type="text/javascript" src="timer.js"></script>
<body>
</body>
</html>
And here is my JavaScript:
// boolean keeps track of timer state
var active = false;
//main function
function start_timer() {
//function active if true
if (active) {
var timer = document.getElementById("my_timer").innerHTML;
var arr = timer.split(":"); //spliting timer into array by ':', so hour goes to arr[0], minutes go to arr[1], etc.
var hour = arr[0]; //getting hour
var min = arr[1]; //minutes
var sec = arr[2]; //seconds
if (sec == 59) {
if (min == 59) {
hour++;
min = 0;
if (hour < 10) hour ="0" + hour;
} else {
min++;
}
if (min < 10) min = "0" + min;
sec = 0;
} else {
sec ++;
if (sec < 10) sec = "0" + sec;
}
//update our html
document.getElementById("my_timer").innerHTML = hour + ":" + min + ":" + sec;
setTimeout(start_timer, 1000); //repeat with speed of 1 second
}
}
//functions to change states - start or pause timer by clicking
function changeState () {
if (active == false) {
active = true;
start_timer();
console.log("Timer has been started");
document.getElementById("control").innerHTML = "PAUSE";
} else {
active = false;
console.log("Timer is on pause");
document.getElementById("control").innerHTML = "START";
}
}
//reset function
function reset() {
document.getElementById("my_timer").innerHTML = "00" + ":" + "00" + ":" + "00";
console.log("Timer has been reset");
}
How would I script a function that would add 2 seconds to the display timer?
Below only works while the timer is running. To get the button to add two seconds whether the timer is running or not, remove the 'if (active){'.
// add two seconds to displayed time
function start_timer(){
if (active) {
var timer = document.getElementById("my_timer").innerHTML;
var arr = timer.split(":"); //spliting timer into array by ':', so hour goes to arr[0], minutes go to arr[1], etc.
var hour = arr[0]; //getting hour
var min = arr[1]; //minutes
var sec = arr[2]; //seconds
if ((sec == 58) || (sec == 59)) {
if (min == 59) {
hour++;
min = 0;
if (hour < 10) hour ="0" + hour;
} else {
min++;
}
if (min < 10) min = "0" + min;
if (sec == 58){
sec = 0;
}
if (sec == 59){
sec = 1;
}
} else {
sec = parseInt(sec) + 2;
if (sec < 10) sec = "0" + sec;
}
//update our html
document.getElementById("my_timer").innerHTML = hour + ":" + min + ":" + sec;
}
}