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

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.

Related

Creating a stopwatch from scratch in JavaScript

By creating variables for milliseconds, seconds, and minutes, I wanted to make a little stopwatch project. The onClick for the button I have is for theTimer():
var milli = 0;
var seconds = 0;
var minutes = 0;
var onOff = 0;
var txtMilli = document.getElementById("txtMilli");
var txtSeconds = document.getElementById("txtSeconds");
var txtMinutes = document.getElementById("txtMinutes");
function theTimer()
{
if (onOff == 0) {
onOff = 1;
timer = setInterval("startCounting()",1);
}
if (onOff == 1) {
onOff == 0;
clearInterval(timer);
}
}
function startCounting()
{
if (milli >999)
{
milli = 0; if (seconds <60) {seconds +=1}
}
else
{
milli +=1;
}
if (seconds >59)
{
seconds = 0; minutes += 1;
}
if (milli > 10)
{
txtMilli.innerHTML = "0" + milli;
}
if (milli < 10)
{
txtMilli.innerHTML = "" + milli;
}
}
Nothing shows up in the console, the problem is that the DIVs never change from 0 when running it.
I managed to fix your code like so:
var milli = 0;
var seconds = 0;
var minutes = 0;
var onOff = 0;
var txtMilli = document.getElementById("txtMilli");
var txtSeconds = document.getElementById("txtSeconds");
var txtMinutes = document.getElementById("txtMinutes");
function startCounting(){
if (milli >999) { milli = 0; if (seconds <60) {seconds +=1} }
else {milli +=1;}
if (seconds >59) {seconds = 0; minutes += 1;}
if (milli > 10) {txtMilli.innerHTML = "0" + milli;}
if (milli < 10) {txtMilli.innerHTML = "" + milli;}
}
function theTimer(){
if (onOff == 0) {
onOff = 1;
timer = setInterval(startCounting, 1);
} else if (onOff == 1) {
onOff = 0;
clearInterval(timer);
}
}
myButton.onclick = theTimer;
There was a bug inside theTimer where you'd set onOff to 1, then immediately check to see if it was 1 and set it back to 0. I fixed this by using else if.
I also changed onOff == 0 (which is a comparison) to onOff = 0 (which is an assignment).
Working JSFiddle: https://jsfiddle.net/k83tvfhc/

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

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

How to show milliseconds in count down timer javascript

I have a javascript code that displays a count down timer from 5 minutes.
This is the code
var mins
var secs;
function cd() {
mins = 1 * m("05"); // change minutes here
secs = 0 + s(":00"); // change seconds here (always add an additional second to your total)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
var timerStr = dis(mins,secs);
$("#countDownTimer").text(timerStr); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
} else {
cd = setTimeout("redo()",1);
}
}
function init() {
cd();
}
window.onload = init;
How can i change the script to show milliseconds too
or is there any simple script to show the count down timer including minutes:seconds:milliseconds
I reworked the code to include milliseconds. Also make sure the setTimer is set correctly.
var mins
var secs;
var ms;
function cd() {
mins = 1 * m("05"); // change minutes here
secs = 0 + s(":00"); // change seconds here (always add an additional second to your total)
ms = 0 + ms(":00");//change millisecons here
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function ms(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs,ms) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs + ":";
}
if(ms <= 9) {
disp += "0" + ms;
} else {
disp += ms;
}
return(disp);
}
function redo() {
ms--;
if(ms == -1) {
ms = 99;
secs--;
}
if(secs == -1) {
secs = 59;
mins--;
}
var timerStr = dis(mins,secs,ms);
document.getElementById('countdown_fld').innerText=timerStr; // setup additional displays here.
if((mins == 0) && (secs == 0) && (ms == 0)) {
} else {
cd = setTimeout("redo()",10); //make sure to set the timer right
}
}
function init() {
cd();
}
You're calling the timeout with a parameter of 1, which means 1millisecond per timer 'event', but you're treating that millisecond event as a full second in your redo() function.
redo() should be:
function redo() {
s -= 0.001; // subtract 1 millisecond
if (s < 0) {
secs = 59.999;
mins--;
}
}
and so on. However, given that running this code every millisecond is going to put a fairly heavy load on the browser, and will not run with exact millisecond precision. What you should be doing is keeping track of TIME - when you start the countdown, record the current system time using the Date() object, which has millisecond precision.
Invoke your redo() at some longer interval than milliseconds (say, every 200ms / 0.2 seconds), and then subtract the system time at that point from the start time of the timer.
How about using one of the many jQuery countdown plugins out there, such as http://keith-wood.name/countdown.html or http://code.google.com/p/jquery-countdown/?
Upon further inspection:
jQuery 1 minute countdown with milliseconds and callback
javascript countdown with showing milliseconds

Categories

Resources