Fix timer starting on page load - javascript

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

Related

Restart countdwon timer on next button click

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>

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

Javascript with count down timer

My problem is that the more I "click" on the Start time button, the faster it counts.
How can I change it to normal 2 minute countdown timer?
Like this: http://www.donothingfor2minutes.com/
My code:
var minute = 1;
var second = 59;
function time(){
setInterval(starttime, 1000);
}
function starttime(){
document.getElementById("timer").innerHTML = minute +" : " + second ;
second--;
if(second == 00) {
minute--;
second = 59;
if (minute == 0) {
minute = 2;
}
}
}
If you want the timer to reset each time you click on the button, try resetting the interval on click:
var minute, second, timer;
function time() {
clearInterval(timer);
minute = 1;
second = 59;
timer = setInterval(updateTime, 1000);
}
function updateTime() {
document.getElementById("timer").innerHTML = minute + " : " + second;
second--;
if (second == 00) {
minute--;
second = 59;
if (minute == 0) {
minute = 2;
}
}
}
What's happening is that you're probably calling time() multiple times, and thereby initiating multiple setInterval calls.
One way to avoid that would be to add a flag timeStarted, which starts the timer only when it is unset:
var minute = 1;
var second = 59;
var timeStarted = false;
function time() {
if(!timeStarted) {
timeStarted = true;
setInterval(starttime, 1000);
}
}
function starttime() {
document.getElementById("timer").innerHTML = minute + " : " + second;
second--;
if (second == 00) {
minute--;
second = 59;
if (minute == 0) {
minute = 2;
}
}
}

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

Disable Back Button in browser Not working

The following code is javascript containing a timer and other 2 functions
`
var sec;
var min;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
//set the timer to the session variable only for the first time
if(isPostBack == 'false'){
sec=second;
min=minute;
}
//set the timer
function timer()
{
if(isPostBack == 'true')
{
sec = second;
min = minute;
}
sec=sec-1;
if(sec < 0)
{
sec=59;
min--;
}
else
{
min=min;
}
if(sec <=9 )
{
sec = "0"+sec;
}
document.getElementById("lblCountDown").innerHTML= "Time Left: "+(min<=9 ? "0" + min : min)+" mins"+" "+sec + " secs";
//copy the value of min and sec in fields
document.getElementById("min").value=min;
document.getElementById("sec").value=sec;
//copy the value of min and sec in session variable
minute = min;
second = sec;
if (min <=0 && sec <= 0)
{
clearInterval(counter);
alert("Times Up!!!. Your Test Will Be Auto Submited");
document.getElementById("Submit").click();
return;
}
}
function showKeyCode(e)
{
var keycode =(window.event) ? event.keyCode : e.keyCode;
if(keycode == 116)
{
alert("Page Cannot be refresh");
event.keyCode = 0;
event.returnValue = false;
return false;
}
}
function disableBackButton()
{
window.history.forward(1);
}
`
Code in aspx.cs file
`<body onload = "disableBackButton()" onkeydown = "showKeyCode()">
back button is not getting disable
can anyone plz suggest the solution?
That code is not going to disable the back button!
That code would have to be on the previous page.

Categories

Resources