Restart countdwon timer on next button click - javascript

i am working on a bid auction website
i have a count down timer script. its working well on load of window, when i click on restart button it should restart the countdown timer from new value but its not working
<script type="text/javascript">
function countDown(hrs,min,sec,gid) {
sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
}
else { min = min; }
if (min == -01) {
min = 59;
hrs = hrs - 1;
}
else { hrs = hrs; }
if (sec<=9) { sec = "0" + sec; }
if (hrs<=9) { hrs = "0" + hrs; }
time = hrs + ":" + (min<=9 ? "0" + min : min) + ":" + sec + "";
if (document.getElementById) { document.getElementById(gid).innerHTML = time; }
SD=window.setTimeout("countDown("+hrs+","+min+","+sec+",'"+gid+"');", 1000);
if (hrs == '00' && min == '00' && sec == '00') { sec = "00"; window.clearTimeout(SD); }
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
countDown(1,0,10,'oneT');
countDown(0,0,28,'twoT');
countDown(0,2,15,'threeT');
});
</script>
<button onclick="countDown(1,0,10,'oneT')">Restart</button>
<div id="oneT" ></div>
<div id="twoT" ></div>
<div id="threeT"></div>
Thanks, Ahsan

<script type="text/javascript">
function resetCountdown() {
if (SD) {
clearTimeout(SD);
}
countDown(1, 0, 10, 'oneT');
}
</script>
<button onclick="resetCountdown()">Restart</button>
<div id="oneT" ></div>
You need to clear the timeout for every variable that you are using in order to work.

The problem is that your onclick event calls countDown without clearing the queued countDown call from setTimeout that was initiated by your original countDown call. This leads to two competing series of calls to countDown. You can see this using your current code when you click "Restart": sometimes the counter will increase and then decrease, as the two competing strings of countDown calls both change the displayed time.
The solution (with minimal code changes), is to store the setTimeout object in a global variable. You can then use clearTimeout to cancel any pending calls to countDown before restarting the timer. This can be done in a new function, restartTimer.
<html>
<script type="text/javascript">
var timers = {};
function countDown(hrs,min,sec,gid) {
sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
}
else { min = min; }
if (min == -01) {
min = 59;
hrs = hrs - 1;
}
else { hrs = hrs; }
if (sec<=9) { sec = "0" + sec; }
if (hrs<=9) { hrs = "0" + hrs; }
time = hrs + ":" + (min<=9 ? "0" + min : min) + ":" + sec + "";
if (document.getElementById) { document.getElementById(gid).innerHTML = time; }
timers[gid]=window.setTimeout("countDown("+hrs+","+min+","+sec+",'"+gid+"');", 1000);
if (hrs == '00' && min == '00' && sec == '00') { sec = "00"; window.clearTimeout(timers[gid]); }
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
countDown(1,0,10,'oneT');
countDown(0,0,28,'twoT');
countDown(0,2,15,'threeT');
});
function restartTimer(hrs, min, sec, gid) {
window.clearTimeout(timers[gid]);
timers[gid] = countDown(hrs, min, sec, gid);
}
</script>
<button onclick="restartTimer(1,0,10,'oneT')">Restart</button>
<div id="oneT" ></div>
<div id="twoT" ></div>
<div id="threeT"></div>
</html>

Related

clearInterval() not working

Session length is the start time of the timer, default is 25. isEven is used to start/stop the timer, if isEven is false, the timer should start, if it is odd it should hit clearInterval, which for some reason is not stopping execution of tick() function (which counts down the timer).
var count = 0;
function countdown(sessionLength) {
var minutes = sessionLength - 1;
var seconds = 60;
var isEven = false;
count++;
if (count % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
var myVar = setInterval(tick, 1000);
if (isEven == false) {
function tick() {
if (seconds > 0) {
seconds--;
} else {
minutes--;
seconds = 59;
}
if (minutes > 0) {
document.getElementById("time").innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + seconds.toString();
} else {
document.getElementById("time").innerHTML =
"0:" + (seconds < 10 ? "0" : "") + seconds.toString();
}
}
} else {
console.log("reached");
clearInterval(myVar);
}
};
Move the tick() function declaration outside of the if block
setInterval variable is a local one. So its value is overwritten every time you call countdown
. The solution would be to initialize myVar outside the function countdown or to make it a global variable like this :
window.myVar =setInterval (tick,1000);
You have also to put this instruction in the first if block, so that it is not overwritten everytime
var count = 0;
function countdown(sessionLength) {
var minutes = sessionLength - 1;
var seconds = 60;
var isEven = false;
count++;
if (count % 2 == 0) {
isEven = true;
} else {
isEven = false;
}
if (isEven == false) {
window.myVar = setInterval(tick, 1000);
function tick() {
if (seconds > 0) {
seconds--;
} else {
minutes--; seconds = 59;
}
if (minutes > 0) {
document.getElementById("time").innerHTML = minutes.toString() + ":" + (seconds < 10 ? "0" : "") + seconds.toString();
} else {
document.getElementById("time").innerHTML = "0:" + (seconds < 10 ? "0" : "") + seconds.toString();
}
}
} else {
console.log("reached");
if (window.myVar){
clearInterval(window.myVar);
window.myVar = null;
}
}
};

How to add a pause/play function to a running setInterval?

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

Button Click shouldn't stack the function it triggers but it does

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.

Java script Timer CountDown

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

Fix timer starting on page load

A simple Javascript timer that runs for 30 seconds and displays a message once it reaches 0. I cant figure out how to get it to start when a button is pressed instead of on pageload. Any help is appreciated :)
<script type="text/javascript">
var sec = 30; // set the seconds
var min = 00; // set the minutes
function countDown() {
sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
} else {
min = min;
}
if (sec<=9) { sec = "0" + sec; }
time = (min<=9 ? "0" + min : min) + " min and " + sec + " sec ";
if (document.getElementById) { theTime.innerHTML = time; }
SD=window.setTimeout("countDown();", 1000);
if (min == '00' && sec == '00') { sec = "00"; window.clearTimeout(SD); alert("Too slow."); }
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
countDown();
});
</script>
<button onclick='countDown();'>Click Me</button>
And just don't call addLoadEvent() at all.
Add event listener to the button in the load function and then call countDown
addLoadEvent(function() {
var el = document.getElementById("startButton");
el.addEventListener("click", countDown, false);
});
Here the full example link
Here's a full sample with start/stop and remaining time display.
var gTimer = null
function endOfTimer() {
console.log("here");
window.alert('Too slow');
}
function start() {
gTimer = window.setTimeout('endOfTimer', 1 * 1000);
}

Categories

Resources