I'm coding a simple countdown timer in javascript, with play and pause buttons. It works fine when I start it, but if I pause/play a few times the timer values changes randomly, I can't figure out why.
Here's my code :
var minutesleft = 60;
var secondsleft = 0;
var millisecondsleft = 0;
var bool = true;
var paused = false;
var end;
var now;
function pause(){
paused = true;
}
function stop(){
end = now;
bool = true;
}
function cd(){
if (bool) {
end = new Date();
end.setMinutes(end.getMinutes()+minutesleft);
end.setSeconds(end.getSeconds()+secondsleft);
end.setMilliseconds(end.getMilliseconds()+millisecondsleft);
bool = false;
}
now = new Date();
diff = end - now;
diff = new Date(diff);
var msec = diff.getMilliseconds();
var sec = diff.getSeconds();
var min = diff.getMinutes();
if (min < 10){
min = "0" + min;
}
if (sec < 10){
sec = "0" + sec;
}
if(msec < 10){
msec = "00" +msec;
}
else if(msec < 100){
msec = "0" +msec;
}
if(now >= end){
clearTimeout(timerID);
document.getElementById("cdtime").innerHTML = 'POLICE IS HERE';
}
else{
document.getElementById("cdtime").innerHTML = min + ":" + sec + ":" + msec;
}
if (paused == false){
timerID = setTimeout("cd()", 10);
}
else {
bool = true;
minutesleft = min;
secondsleft = sec;
millisecondsleft = msec;
}
paused = false;
}
Here's a fiddle : https://jsfiddle.net/cw3s5124/
Thanks in advance
The main issue with the jumping numbers was due to string concatenation and then using that string in the date functions. Parts of the code such as this:
if (min < 10){
min = "0" + min;
}
An example proving why this is happening
var end1 = new Date();
var minutesleft1 = 9;
console.log("Minutes to assign to current time");
console.log(end1.getMinutes() + minutesleft1); // Logs expected amount of minutes to calculate
end1.setMinutes(end1.getMinutes() + minutesleft1);
var end2 = new Date();
var minutesleft2 = "09";
console.log("Wrong Minutes to assign to current time");
console.log(end2.getMinutes() + minutesleft2); // Logs big number
end2.setMinutes(end2.getMinutes() + minutesleft2);
console.log(end1); // Logs expected result
console.log(end2); // Logs a time a day or so in the future
■
Explanation: If you were to set your start timer to 9 in the minutes var, it would immediately need to be padded with a 0 for display. Since you are now setting the minutesleft variable to "09" you are effectively doing 9 + "09" when you call end.setMinutes(end.getMinutes()+minutesleft);
Once you concatenate a string "0" to the number, you are effectively trying to do numeric operations with a string, which is causing unexpected results. This wasn't happening at the start, because your if statements weren't running yet and thus the min, sec, and msec vars were still numeric. You should only pad the numbers when displaying them, not in the calculations themselves.
I replaced the string concatenation with a padding function borrowed from this post.
I also added a play function to reset your pause parameter. This makes the code more readable and easier for me to understand. Also, change it to paused at the start because the timer isn't running yet.
var minutesleft = 10;
var secondsleft = 05; // This would normally just be returned as 5, that's why we need the pad function for display
var millisecondsleft = 0;
var firstCall = true;
var paused = true;
var end;
var now;
function pause() {
paused = true;
}
function play() {
if (paused === false) // Shorcut out because we are already running
return;
paused = false;
cd();
}
function stop() {
end = now;
paused = true;
cd();
}
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("cdtime").innerHTML = pad(minutesleft, 2) + ":" + pad(secondsleft, 2) + ":" + pad(millisecondsleft, 2);
});
function cd() {
if (firstCall) {
end = new Date();
end.setMinutes(end.getMinutes() + minutesleft);
end.setSeconds(end.getSeconds() + secondsleft);
end.setMilliseconds(end.getMilliseconds() + millisecondsleft);
firstCall = false;
}
now = new Date();
diff = end - now;
diff = new Date(diff);
var msec = diff.getMilliseconds();
var sec = diff.getSeconds();
var min = diff.getMinutes();
if (now >= end) {
clearTimeout(timerID);
document.getElementById("cdtime").innerHTML = 'POLICE IS HERE';
} else {
document.getElementById("cdtime").innerHTML = pad(min, 2) + ":" + pad(sec, 2) + ":" + pad(msec, 2);
}
if (paused === false) {
timerID = setTimeout("cd()", 10);
} else {
bool = true;
minutesleft = min;
secondsleft = sec;
millisecondsleft = msec;
}
}
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
<body>
<div id='timer'>
<button class='playerButtons' id='playT' type='submit' onclick='play()'>Play</button>
<button class='playerButtons' id='pauseT' type=' submit' onclick='pause()'>Pause</button>
<button class='playerButtons' id='stopT' type='submit' onclick='stop()'>Stop</button>
<div id='cdtime'></div>
</div>
</body>
You reset paused and bool in the wrong spot. If you look at the JsFiddle, you can see what needs to be removed
var minutesleft = 60;
var secondsleft = 0;
var millisecondsleft = 0;
var bool = true;
var paused = true;
var end;
var now;
function pause(){
paused = true;
//bool = false; //shouldn't be here (move to stop function)
}
function play(){
if ( paused === true){
paused = false;
bool = true;
cd();
}
}
function stop(){
end = now;
bool = false; //add here
}
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("cdtime").innerHTML = minutesleft + ":" + secondsleft + "0:" + millisecondsleft + "0";
});
function cd(){
if (bool) {
end = new Date();
end.setMinutes(end.getMinutes()+minutesleft);
end.setSeconds(end.getSeconds()+secondsleft);
end.setMilliseconds(end.getMilliseconds()+millisecondsleft);
bool = false;
}
now = new Date();
diff = end - now;
diff = new Date(diff);
var msec = diff.getMilliseconds();
var sec = diff.getSeconds();
var min = diff.getMinutes();
if (min < 10){
min = "0" + min;
}
if (sec < 10){
sec = "0" + sec;
}
if(msec < 10){
msec = "00" +msec;
}
else if(msec < 100){
msec = "0" +msec;
}
if(now >= end){
clearTimeout(timerID);
document.getElementById("cdtime").innerHTML = 'POLICE IS HERE';
}
else{
document.getElementById("cdtime").innerHTML = min + ":" + sec + ":" + msec;
}
if (paused === false){
timerID = setTimeout("cd()", 10);
}
else {
bool = true;
minutesleft = min;
secondsleft = sec;
millisecondsleft = msec;
}
//paused = false; //shouldn't be here
}
<body>
<div id='timer'>
<button class='playerButtons' id='playT' type='submit' onclick='play()'>Play</button>
<button class='playerButtons' id='pauseT' type=' submit'onclick='pause()'>Pause</button>
<button class='playerButtons' id='stopT' type='submit' onclick='stop()'>Stop</button>
<div id='cdtime'></div>
</div>
</body>
https://jsfiddle.net/cw3s5124/27/
Related
I have created a countdown timer and am trying to add 2 minutes into the existing timer to extend the timer.
My Code
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
$(document).ready(function() {
var counter = 0;
var display = document.querySelector('#time'),
//timer = new CountDownTimer(600);
timer = new CountDownTimer(125); // for debug
timer.onTick(format).onTick(restart).start();
function restart() {
if (this.expired()) {
alert("Expired");
}
}
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
alert("Extending Time");
counter++;
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span> minutes
I managed to trigger an event that after 2 minutes will show an alert that the time will be extended, but so far, I can't think of any method or functions I can use to add the extra time. Is there any way I can do this?
Add code as following:
CountDownTimer.prototype.reset = function (duration) {
this.duration = duration;
}
and rewrite function format as :
function format(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ':' + seconds;
if (minutes < 2) {
if (counter == 0) {
//alert("Extending Time");
timer.reset(timer.duration + 120);
counter++;
}
}
}
You can add code in CountDownTimer.prototype.start before setTimeout like:
this.instance = setTimeout(...)
add function:
CountDownTimer.prototype.kill = function() {
clearTimeout(this.instance)
}
call function kill to stop timer permanently.
I'm trying to create a simple vanilla JS stopwatch. Managed to make it work however when I click my reset button, the value returns my innerHTML change, however it flashes for a quick second before returning a value of 00:00:1 and not 00:00:00. I would have to click it two times before it resets correctly. However, when I pause my timer then reset, it works perfectly. Where is the flaw in my code?
Code:
var status = 0;
var time = 0;
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
time = 0;
status = 0;
document.getElementById('label').innerHTML = '00:00:00';
document.getElementById('start').disabled = false;
}
function timer() {
if (status == 1) {
setTimeout(function() {
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
It's because of the setTimeout, since it's scheduled to run each 100ms, it will run once after you click reset (after a 100ms). In order to prevent it from running after reset, you can store the timeout in a variable and stop it using clearTimeout:
var status = 0;
var time = 0;
var t; // the timeout
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
time = 0;
status = 0;
clearTimeout(t); // stop the timeout
document.getElementById('label').innerHTML = '00:00:00';
document.getElementById('start').disabled = false;
}
function timer() {
if (status == 1) {
t = setTimeout(function() { // start the timeout
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
The reason is that I believe there is a slight latency and you aren't actually clearing the timeout that gets run when you start. It's good practice to keep track of the timeout ID and then clear it appropriately when you need to.
var status = 0;
var time = 0;
var timeoutId;
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
time = 0;
status = 0;
clearTimeout(timeoutId);
document.getElementById('label').innerHTML = '00:00:00';
document.getElementById('start').disabled = false;
}
function timer() {
if (status == 1) {
timeoutId = setTimeout(function() {
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
Its realy simple you have to remove the setTimeout callback function
var timerObj = null; // NEW LINE
var status = 0;
var time = 0;
document.getElementById('start').addEventListener('click', start);
document.getElementById('pause').addEventListener('click', pause);
document.getElementById('reset').addEventListener('click', reset);
function start() {
status = 1;
document.getElementById('start').disabled = true;
timer();
}
function pause() {
status = 0;
document.getElementById('start').disabled = false;
}
function reset() {
clearTimeout(timerObj ); // new LINE
status = 0;
document.getElementById('start').disabled = false;
time = 0;
document.getElementById('label').innerHTML = '00:00:00';
}
function timer() {
if (status == 1) {
timerObj = setTimeout(function() { // changed LINE
time++;
var min = Math.floor(time / 10 / 60);
var sec = Math.floor(time / 10 % 60);
var mill = time % 10;
if (min < 10) {
min = '0' + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('label').innerHTML = min + ':' + sec + ':' + mill;
timer();
}, 100);
}
}
<div id="wrapper">
<h1 id="label">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
So I am trying to create a pomodoro timer. The website currently looks and functions like this: POMODOROone
My timer is counting down correctly so far. However, when I try to add a pause and resume functionality, it breaks. I have tried multiple ways but I haven't had much success. So I removed all my attempts and I have the code for what is working so far.
So, my question is how would I add a pause/resume functionality to my timer? Also, how would I make my timer stop when I click on any of the positive and negative spans or the inputs?
Here is the Javascript:
//decreases break time by 5 mins
function decreaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("breakInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//increases break time by 5 mins
function increaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("breakInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//decreases session time by 5 mins
function decreaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//increases session time by 5 mins
function increaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//countdown timer
function start() {
var sec = 60;
var timerParagraph = document.getElementById("timerParagraph").innerHTML;
var min = timerParagraph.substring(0, timerParagraph.indexOf(":"));
var time = min * 60;
min = parseInt(min,10)-1;
setInterval(function() {
sec = sec - 1;
if (sec < 0) {
min -= 1;
sec = 59;
}
if (min < 0 && sec < 0) {
clearInterval(start());
}
var temp;
if (min.toString().length == 1 && sec.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + sec;
} else if (sec.toString().length == 1 && min.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = min + ":" + "0" + sec;
} else if (min.toString().length == 1 && sec.toString().length ==1) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + "0" + sec;
} else {
document.getElementById("timerParagraph").innerHTML = min + ":" + sec;
}
},1000);
}
New Updated Code:
//decreases break time by 5 mins
function decreaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("breakInput").value = new_time;
clearInterval(timer);
document.getElementById("timerParagraph").innerHTML = new_time+":00";
}
//increases break time by 5 mins
function increaseBreak() {
var time = document.getElementById("breakInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("breakInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
clearInterval(timer);
timer = null;
}
//decreases session time by 5 mins
function decreaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time - 5;
if (time == 0) {
return 0;
}
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
clearInterval(timer);
}
//increases session time by 5 mins
function increaseSession() {
var time = document.getElementById("sessionInput").value;
time = parseInt(time, 10);
var new_time = time + 5;
document.getElementById("sessionInput").value = new_time;
document.getElementById("timerParagraph").innerHTML = new_time+":00";
clearInterval(timer);
}
//countdown timer
var timer = null;
var sec = 60;
function start() {
var timerParagraph = document.getElementById("timerParagraph").innerHTML;
var min = timerParagraph.substring(0, timerParagraph.indexOf(":"));
min = parseInt(min,10)-1;
function onTimer() {
sec = sec - 1;
if (sec < 0) {
min -= 1;
if (min == 0 && sec == 0) {
// When min and second equals zero, timer stops
clearInterval(timer);
}
sec = 59;
}
if (min.toString().length == 1 && sec.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + sec;
} else if (sec.toString().length == 1 && min.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = min + ":" + "0" + sec;
} else if (min.toString().length == 1 && sec.toString().length ==1) {
document.getElementById("timerParagraph").innerHTML = "0" + min + ":" + "0" + sec;
} else {
document.getElementById("timerParagraph").innerHTML = min + ":" + sec;
}
}
timer = setInterval(onTimer,1000);
console.log("Start timer");
// when the div is clicked, the timer starts and stops.
document.getElementById("timerDiv").onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
} else {
timer = setInterval(onTimer,1000);
console.log("Resume timer");
}
}
}
This updated code works for the following new actions:
1. When the timer starts playing, and if the timerDiv is clicked, it will pause.
2. And when clicked again, it will resume.
Now, when I click on the positive and negative signs and change the time, it changes the time like it should and clears the interval like it is called. However, when I click on the timerDiv again, instead of playing from the start, it resumes playing the time from where it left off. How would I make it so that when I click on the timerDiv again, it counts down from the new time instead of resuming previous time.
Here is an implementation called interruptible-timer:
// A timer which can be interrupted and picks up where you left off.
//
// Usage:
// ```
// var timer = interruptibleTimer(task, 5000);
// timer.start(); // Start the timer, or resume it after stopping.
// timer.stop(); // Timer continues to run, but task will not be called.
// timer.run(); // Run task now, and start timer again from now.
// timer.reset(); // Stop the timer and reset it to 0.
// ```
var set = window.setTimeout;
var clear = window.clearTimeout;
function interruptibleTimer(fn, interval) {
var recent = 0;
var timer;
// PRIVATE FUNCTIONS
function now() { return +new Date(); }
function delay() { return recent ? Math.max(0, recent + interval - now()) : interval; }
function schedule() { timer = set(run, delay()); }
// PUBLIC APIs
function start() { if (!timer) schedule(); }
function stop() { clear(timer); timer = 0; }
function run() { fn(); recent = now(); schedule(); }
function reset() { stop(); recent = 0; }
return {start, stop, run, reset};
}
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval
The way you set your interval and clear it inside of the start() function doesn't make much sense and is probably the cause of your troubles.
The function called every second should be stored with a function name.
/*
A wrapper variable is used to keep variables in scope so clearinterval can be used and variables don't interact outside of 'T'.
*/
var T = {
sec: null,
timerParagraph: null,
min: null,
time: null,
interval: null,
//countdown timer
start: function(){
T.interval = setInterval(T.tickClock,1000);
},
pause: function(){
clearInterval(T.interval);
},
reset: function(){
T.sec = 60;
T.timerParagraph = document.getElementById("timerParagraph").innerHTML;
T.min = T.timerParagraph.substring(0, T.timerParagraph.indexOf(":"));
T.time = T.min * 60;
T.min = parseInt(T.min,10)-1;
},
tickClock: function(){
T.sec = T.sec - 1;
if (T.sec < 0) {
T.min -= 1;
T.sec = 59;
}
if (T.min < 0 && T.sec < 0) {
clearInterval(T.interval);
}
if (T.min.toString().length == 1 && T.sec.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = "0" + T.min + ":" + T.sec;
} else if (T.sec.toString().length == 1 && T.min.toString().length == 2) {
document.getElementById("timerParagraph").innerHTML = T.min + ":" + "0" + T.sec;
} else if (T.min.toString().length == 1 && T.sec.toString().length ==1) {
document.getElementById("timerParagraph").innerHTML = "0" + T.min + ":" + "0" + T.sec;
} else {
document.getElementById("timerParagraph").innerHTML = T.min + ":" + T.sec;
}
}
/*
Use T.reset() to set the clock back to the beginning. Use T.start to begin the interval and T.pause to stop the interval.
You may need to record how far within a second the pause is used so you can offset the second when you start again.
This would mean having a settimeout which counts in milliseconds or something.
*/
}
I haven't tested this code so beware of potential typos, although I did double check for those.
To make the timer pause use onclick="T.pause()" within the elements you want to have that functionality.
Or within javascript using
element.onclick = function(){
T.pause();
}
http://www.w3schools.com/jsref/event_onclick.asp
I'm making an timer in Javascript which already works well the only problem is when I keep hitting the
"Start" button it keeps stacking the count function and will count at an higher and higher speed. Tried multiple things to stop it but can't manage myself.
JS:
var startknop = document.getElementById("start");
var stopknop = document.getElementById("stop");
var hour = 0;
var min = 0;
var sec = 0;
startknop.onclick = function()
{
intervalId = setInterval(count, 1000);
}
stopknop.onclick = function()
{
clearInterval(intervalId);
}
counter.innerHTML = hour + "0:" + min + "0:" + sec + "0";
function count() {
sec++;
if(sec <= 9)
{
var seco = "0" + sec;
}
else
{
seco = sec;
}
if(min <= 9)
{
var mino = "0" + min;
}
else
{
mino = sec;
}
if(hour <= 9)
{
var houro = "0" + hour;
}
else
{
houro = hour;
}
if(sec == 60){
sec = 0;
min += 1;
}
if(min == 60){
min = 0;
hour += 1;
}
counter.innerHTML = houro + ":" + mino + ":" + seco;
}
var running = false;
startknop.onclick = function()
{
if(!running)
{
running=true;
intervalId = setInterval(count, 1000);
}
}
when timer is finished set running false.
Wrap the setInterval in an if block with a boolean to check if initialised. You are starting multiple timers, so stop only stops the last one assigned to your global variable. You could also set intervalId to -1 and do a check on it being >0, setting it back to -1 after the clearInterval call.
I'm creating java script count down timer and it works up to 60 seconds correctly and after that its not working.
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
var val = document.getElementById("LabelTimer");
if (val != null) {
var PopUpTimeDuration = 2;
countdown(parseInt(PopUpTimeDuration));
}
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1
seconds--;
counterVal.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
var result = counterVal.innerHTML;
if (result == "0:00") {
clearInterval(counter);
CloseIdlePage();
}
if (seconds > 0) {
setTimeout(tick, 1000);
} else {
debugger;
if (mins >= 1) {
countdown(mins - 1);
}
}
}
tick();
}
When i run this program this start 1:59 and it continues up to 1:01. after that this display value rest to 1:59. (not 0:59). what i did wrong in here?
Fiddle demo is in Here: in here you can see two values are blinking each other
Here's how I'd implement this. Hopefully the comments are sufficient. It needs an element in the page with ID "counterDiv" to write the values to.
function quickCount(mins) {
// Keep some values in a closure
var el = document.getElementById('counterDiv');
var secs = 0;
// Helper to pad single digit numbers
function z(n){return (n<10? '0':'') + n}
// Keep a reference to the interval
var timer = setInterval(function() {
// Write the values
el.innerHTML = mins + ':' + z(secs);
// Decremement seconds
--secs;
// If finished a minute, decrement minut
if (secs < 0) {
if (mins) {
--mins;
secs = 59;
// If finsihed minutes too, cancel timer
} else {
timer && clearInterval(timer);
}
}
// Run at about every second
}, 1000);
}
window.onload = function() {
quickCount(2);
}
HTH
<head>
<script type="text/javascript">
function timer()
{
var val = document.getElementById("LabelTimer");
if (val !== null)
{
var PopUpTimeDuration = 2;
countdown(parseInt(PopUpTimeDuration));
}
}
function countdown(minutes)
{
var seconds = 60;
var mins = minutes;
function tick()
{
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1;
seconds--;
var t=current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
counterVal.value = t;
var result = counterVal.innerHTML;
if (result === "0:00")
{
CloseIdlePage();
}
if (seconds > 0)
{
setTimeout(tick, 1000);
}
else
{
if (mins > 1)
{
countdown(mins - 1);
}
}
}
tick();
}
</script>
</head>
<body>
<div>TODO write content</div>
<input type="text" id="LabelTimer" value="yooo">
<input type="text" id="lblCountDown">
<input type="button" value="try" onclick="timer();" />
</body>
I resolved this as follows:
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
var IsFunctionCalled = false;
function timer() {
var val = document.getElementById("LabelTimer");
if (val != null) {
var PopUpTimeDuration = 2;
if (IsFunctionCalled == false) {
IsFunctionCalled = true
countdown(parseInt(PopUpTimeDuration));
}
}
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counterVal = document.getElementById("lblCountDown");
var current_minutes = mins - 1
seconds--;
counterVal.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
var result = counterVal.innerHTML;
if (result == "0:00") {
clearInterval(counter);
CloseIdlePage();
}
if (seconds > 0) {
setTimeout(tick, 1000);
// tick()
} else {
if (mins >= 1) {
countdown(mins - 1);
}
}
}
tick();
}
See here for Demo