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
);
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'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>
I'm working on a pomodoro clock, everthing is working well but when the user clicks to run the the counter more than once I get two counters working I would like to pause the counter and not start another.
function countdown(minutes) {
let seconds = 60;
let mins = minutes;
function tick() {
let current_minutes = mins-1;
seconds--;
time.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
if(mins > 1){
countdown(mins-1);
}
}
console.log(mins);
if (seconds === 0 && mins === 1) {
time.innerHTML = `${sessionLength}:00`;
rounds++;
console.log(rounds);
PlaySound(sound);
}
}
tick();
}
how can I accomplish this?
Why not use setInterval?
var myPomodoro = setInterval(function(){
//... run code in here every 60 seconds
}, 60000);
// stop the timer
clearInterval(myPomodoro);
I want to create a simple countdown timer in javascript or jquery.
I had implemented it using JS but what issue I am facing is if user refreshes the page then timer gets the refresh.
What I want is timer should not get the refresh.
Say timer is 5 min and if user refresh pages after 1 min the timer should continue to start from 4 min instead of 5 mins.
Here is code snippiet.
Its refresh the timer on page refresh.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
}
}
tick();
}
countdown(2);
<div id="timer">2:00</div>
You just update the sessionStorage along with your counter and read it on starting the counter. Unfortunately the related snippet does not work on stackoverflow due to crossdomain policies - so here on codepen https://codepen.io/anon/pen/opNpVe
function countdown(seconds) {
seconds = parseInt(sessionStorage.getItem("seconds"))||seconds;
function tick() {
seconds--;
sessionStorage.setItem("seconds", seconds)
var counter = document.getElementById("timer");
var current_minutes = parseInt(seconds/60);
var current_seconds = seconds % 60;
counter.innerHTML = current_minutes + ":" + (current_seconds < 10 ? "0" : "") + current_seconds;
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
tick();
}
countdown(120);
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");
}