Reset multiple timers in JS - javascript

I try to create a website with multiple timers. I used a script from a website.
But in this script is it not possible to reset one timer or both timers.
I want to start timer1 again from the beginning, so I have to reset the timer first.
How can I reset the timer/s to start it with a new value??
In the end, I want to start Timer1, after that start Timer2 with the remaining time from Timer1 + the new time of Timer2.
function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);
// Set the timer
var interval = setInterval(function() {
if (seconds == 0) {
if (minutes == 0) {
(el.innerHTML = "STOP!");
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
//Start as many timers as you want
var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');
start1.onclick = function() {
countdown('countdown1', 0, 15);
}
start2.onclick = function() {
countdown('countdown2', 0, 10);
}
<html>
<head>
</head>
<body>
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
</body>
</html>
Thanks for your help

You can bind the interval as a property to the element itself.
if ( el.interval )
{
clearInterval( el.interval );
}
// Set the timer
var interval = el.interval = setInterval(function() {
Demo
function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);
if ( el.interval )
{
clearInterval( el.interval );
}
// Set the timer
var interval = el.interval = setInterval(function() {
if (seconds == 0) {
if (minutes == 0) {
(el.innerHTML = "STOP!");
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
//Start as many timers as you want
var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');
start1.onclick = function() {
countdown('countdown1', 0, 15);
}
start2.onclick = function() {
countdown('countdown2', 0, 10);
}
<html>
<head>
</head>
<body>
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
</body>
</html>

You need a return and store a reference to your variable that holds the interval (interval) you can then call clearinterval on the handle:
The relevant changes are:
//variables to hold the intervals
var countdown1Interval;
var countdown2Interval;
start1.onclick = function() {
countdown1Interval = countdown('countdown1', 0, 15);
}
start2.onclick = function() {
countdown2Interval = countdown('countdown2', 0, 10);
}
//event to reset
resetBoth.onclick = function(){
//null check because the button might not of been pressed
if (countdown1Interval){
clearInterval(countdown1Interval);
countdown1Interval = undefined;
}
if (countdown2Interval){
clearInterval(countdown2Interval);
countdown2Interval = undefined;
}
}
You also need to return the interval handle in countdown (return interval;)
Full snippet
function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);
// Set the timer
var interval = setInterval(function() {
if (seconds == 0) {
if (minutes == 0) {
(el.innerHTML = "STOP!");
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
return interval;
}
//Start as many timers as you want
var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');
var resetBoth = document.getElementById('resetBoth');
var countdown1Interval;
var countdown2Interval;
start1.onclick = function() {
countdown1Interval = countdown('countdown1', 0, 15);
}
start2.onclick = function() {
countdown2Interval = countdown('countdown2', 0, 10);
}
resetBoth.onclick = function(){
if (countdown1Interval){
clearInterval(countdown1Interval);
countdown1Interval = undefined;
}
if (countdown2Interval){
clearInterval(countdown2Interval);
countdown2Interval = undefined;
}
}
<html>
<head>
</head>
<body>
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
<input id="resetBoth" type="button" value="Stop both timers" />
</body>
</html>

Related

prevent timer to reset after page refresh site

I have count-up timer and it reset every time after refreshing page or closing tab how can I can continue timer after refreshing or closing page so that after that i can insert that time in database.
I want to also set setInterval for after serval time to update time and store that time .
here is html code :
var h1 = document.getElementById("displaytime"),
start = document.getElementById("start"),
reset = document.getElementById("reset"),
pause = document.getElementById("pause"),
reset_timer = document.getElementById("displaytime"),
seconds = 0,
minutes = 0,
hours = 0,
count = 0,
t = -1;
function timer() {
t = setTimeout(add, 1000);
}
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent =
(hours ? (hours > 9 ? hours : "0" + hours) : "00") +
":" +
(minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" +
(seconds > 9 ? seconds : "0" + seconds);
timer();
}
function display_timer() {
count++;
console.log(displaytime);
}
setInterval(display_timer ,5000);
start.addEventListener("click", function() {
seconds = 0; minutes = 0; hours = 0;
clearInterval(t);
timer();
});
reset.addEventListener("click", function() {
clearTimeout(t);
reset_timer.innerHTML = '00:00:00';
pause.innerHTML = 'Pause';
});
pause.addEventListener('click', function(e) {
if (t == -1) {
pause.innerHTML = 'Pause';
timer();
} else {
pause.innerHTML = "Resume";
clearInterval(t);
t = -1;
}
});
<html>
<head>
<title>Timer</title>
</head>
<body>
<div class="Timer">
<section id="stopWatch">
<h1 id="displaytime">00:00:00</h1>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="reset" >Reset</button>
</section>
</div>
</body>
</html>

stopwatch not functioning properly

I'm just starting with javascript, I've been trying to make a simple stopwatch, I found a couple of ways to do it , then I came across this function ... the code doesn't work as a stopwatch unless we return a function , can somebody help me understand why????
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return ()=>{console.log(i);}
};
setTimeout(tick(i), 500 * i);
}
You should use setInterval and clearInterval for your case.
var i = 10;
var tick = function(i) {
return ()=>{
console.log(i--);
if(i == 0) clearInterval(timer);
}
};
var timer = setInterval(tick(i), 500);
If you want to have stopwatch, you can clearInterval in stop button click event
function stop(){
clearInterval(timer);
}
Update:
I combined Start and Stop in only one button using addEventListener and removeEventListener
var i = 1;
var timer;
var tick = function(i) {
return ()=>{
console.clear();
console.log(i++);
//if(i == 0) clearInterval(timer);
}
};
function start(){
document.getElementById("start").disabled = true;
document.getElementById("stop").disabled = false;
timer = setInterval(tick(i), 500);
}
function stop(){
clearInterval(timer);
document.getElementById("stop").disabled = true;
document.getElementById("start").disabled = false;
}
(function() {
document.getElementById("start2").addEventListener("click", start2);
})();
function start2(){
timer = setInterval(tick(i), 500);
document.getElementById("start2").innerHTML = "Stop";
document.getElementById("start2").removeEventListener("click", start2);
document.getElementById("start2").addEventListener("click", stop2);
}
function stop2(){
clearInterval(timer);
document.getElementById("start2").innerHTML = "Start";
document.getElementById("start2").removeEventListener("click", stop2);
document.getElementById("start2").addEventListener("click", start2);
}
<button id="start" onclick="start()">Start</button>
<button id="stop" onclick="stop()">Stop</button>
<h2>Combine Start and Stop</h2>
<button id="start2" >Start</button>
Because setTimeout first parameter has to be a function.
Your code works because it immediately executes the tick(i) function, which returns a function and that one is used 500ms later as callback.
below code will help you
<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</pre>
<script>
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
start.onclick = function(){
timer();
start.disabled=true;
}
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
start.disabled=false;
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>

Minutes not showing on count-up timer

I'm working with the following script for a count-up timer. It has no problem counting up in seconds but I'm having trouble getting it to display minutes. For example 1:35 (one minute and 35 seconds)
Any suggestions would be appreciated. Thanks in advance.
var clicked = false;
var sec = 00;
var min = 00;
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
} else if (clicked === true) {}
}
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML = 0;
clicked = false;
}
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function() {
countUp();
}, 1000);
function countUp() {
second++;
if (second == 59) {
second = 00;
min = min + 1;
}
if (second == 10) {
zeroPlaceholder = '';
} else
if (second == 00) {
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min + ':' + zeroPlaceholder + second;
}
<div class="timer">
<div id="timer">0:00</div>
<input type="button" id="btnParentButton" value="start timer" onClick="startClock()"/>
Hope this can help you.
The better way is to have your minutes and secs as global variable and simple function for each button
EDIT
Update code using pure JS
var min = 0;
var sec = 0;
var timer = undefined;
var isStarted = false;
function startcount(){
sec++;
if(sec==60)
{
sec=0;
min++;
}
updateClock();
}
function updateClock(){
var displaySec = sec < 10 ? "0" + sec : sec;
var displayMin = min < 10 ? "0" + min : min;
document.getElementById("count").innerHTML = displayMin + " : " + displaySec;
}
function start(){
if(timer == undefined || !isStarted){
timer = setInterval(function(){
startcount();
},1000);
}
isStarted = true;
}
function stop(){
isStarted = false;
clearInterval(timer);
}
function reset(){
stop();
min=sec=0;
timer = undefined;
updateClock();
}
updateClock();
<div id="count"></div>
<button class="start" onClick="start()">Start</button>
<button class="stop" onClick="stop()">Stop</button>
<button class="reset" onClick="reset()">Reset</button>
Put count-up instead id=timer
var clicked = false;
var sec = 00;
var min = 00;
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
} else if (clicked === true) {}
}
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML = 0;
clicked = false;
}
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function() {
countUp();
}, 1000);
function countUp() {
second++;
if (second == 59) {
second = 00;
min = min + 1;
}
if (second == 10) {
zeroPlaceholder = '';
} else
if (second == 00) {
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min + ':' + zeroPlaceholder + second;
}
<div class="timer">
<div id="count-up">0:00</div>
<input type="button" id="btnParentButton" value="start timer" onClick="startClock()"/>

Reset countdown interval with clearInterval doesn't work

I don't know how to reset ongoing counter. I have two counters on my page. It seems it works properly, but when I want to set new value to counter2 when it is still counting down, I see in my div two counting times. New and old one.
var interval1;
var interval2;
function countdown(element, minutes, seconds, timer) {
var el = document.getElementById(element);
clearInterval(timer);
timer = setInterval(function() {
if(seconds == 0) {
if(minutes == 0) {
(el.innerHTML = "---");
clearInterval(timer);
return;
}
else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
}
else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
function setCounter1(mins) {
countdown('timeLeft', mins, 00, interval1);
}
function setCounter2(mins) {
countdown('timeLeft2', mins, 00, interval2);
}
If for example I have set counter2 for 10mins, and after a minute I call setCounter2(3), I see in my timeLeft2 div two counters.
How can I reset ongoing counter?
Thanks for your help!
Reassigning an argument variable inside a function does not modify the argument outside of the function. You can see a demonstration of that fact here : http://jsfiddle.net/t6z5324y/
var outsideVariable = 0;
console.log('start', outsideVariable);
function foo(insideVariable) {
console.log('before', insideVariable);
insideVariable = 1;
console.log('before', insideVariable);
}
foo(outsideVariable);
console.log('end', outsideVariable);
But you can pass an object as an argument, and modify a member of that object inside the function. The solution will then be:
var intervalHolder1 = {timer: null};
var intervalHolder2 = {timer: null};
function countdown(element, minutes, seconds, timerHolder) {
//stuff
clearInterval(timerHolder.timer);
timerHolder.timer = setInterval(function() {
//stuff
}, 1000);
}
function setCounter1(mins) {
countdown('timeLeft', mins, 00, intervalHolder1);
}
function setCounter2(mins) {
countdown('timeLeft2', mins, 00, intervalHolder2);
}
I would do it by defining an array of Interval outside (how many you need) and making your function pass the Index of the Interval rather then the interval itself.
var interval1;
var interval2;
var arrayInterval = [interval1, interval2];
function countdown(element, minutes, seconds, timerId) {
var el = document.getElementById(element);
clearInterval(arrayInterval[timerId]);
arrayInterval[timerId] = setInterval(function() {
if (seconds == 0) {
if (minutes == 0) {
(el.value = "---");
clearInterval(arrayInterval[timerId]);
return;
} else {
minutes--;
seconds = 60;
}
}
if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.value = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
function setCounter1(mins) {
countdown('timeLeft', mins, 00, 0);
}
function setCounter2(mins) {
countdown('timeLeft2', mins, 00, 1);
}

Time to start only after button click

http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/

Categories