Javascript Timer project: why is clearInterval not working? - javascript

I am a beginner trying to learn JavaScript. My project is to make a stopwatch with stop, reset, and go.
For some reason, I can't figure out how to get clearInterval() to stop the goFunction. Any help would be appreciated.
var min = 00
var sec = 00
var ms = 00
function goFunction() {
var swTimer = setInterval(addTime, 10)
function addTime() {
if (ms < 99) {
ms++
} else {
sec += 1
ms = 0
}
if (sec > 59) {
min += 1
sec = 0
}
msShow = (ms < 10) ? "0" + ms : ms
secShow = (sec < 10) ? "0" + sec : sec
minShow = (min < 10) ? "0" + min : min
document.getElementById("numbers").innerHTML = minShow + ":" + secShow + ":" + msShow
}
}
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
<div class="controls">
<button onclick="goFunction()" class="button button1">GO</button>
<button onclick="resetFunction()" class="button button2">RESET</button>
<button onclick="stopFunction()" class="button button3">STOP</button>
<div class="display" id="numbers">00:00:00</div>
</div>

Declare your swTimer outside goFunction
<div class = "controls">
<button onclick="goFunction()" class="button button1">GO</button>
<button onclick="resetFunction()" class="button button2">RESET</button>
<button onclick="stopFunction()" class="button button3">STOP</button>
<div class="display" id = "numbers">00:00:00</div>
</div>
<script>
var min = 00
var sec = 00
var ms = 00
var swTimer
function goFunction() {
swTimer= setInterval(addTime, 10)
function addTime() {
if (ms < 99) {
ms++
} else {
sec+=1
ms = 0
}
if (sec >59 ) {
min+=1
sec=0
}
msShow = (ms<10) ? "0" + ms : ms
secShow = (sec<10) ? "0" + sec : sec
minShow = (min<10) ? "0" + min : min
document.getElementById("numbers").innerHTML = minShow + ":" + secShow + ":" + msShow
}
}
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
</script>

Because swTimer is not global = it's declared and scoped at goFunction and is not defined/accessible in stopFunction.
Set it outside the functions (my opinion: before - where min, sec and ms are declared).

The problem is that swTimer is inside the goFunction block, declare swTimer as a global variable.
var min = 0;
var sec = 0;
var ms = 0;
function addTime() {
if (ms < 99) {
ms++
} else {
sec+=1
ms = 0
}
if (sec >59 ) {
min+=1
sec=0
}
msShow = (ms<10) ? "0" + ms : ms
secShow = (sec<10) ? "0" + sec : sec
minShow = (min<10) ? "0" + min : min
document.getElementById("numbers").textContent = minShow + ":" + secShow + ":" + msShow
}
var swTimer = setInterval(addTime, 1000);
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
window.onload = addTime();
<p id="numbers"></p>
<button onclick="stopFunction()">Go!</button>

The interval won't get cleared because it is locally scoped. You defined in a function which means it cannot be globally accessed in another function a solution would be
var min = 00
var sec = 00
var ms = 00
function addTime() {
if (ms < 99) {
ms++
} else {
sec+=1
ms = 0
}
if (sec >59 ) {
min+=1
sec=0
}
msShow = (ms<10) ? "0" + ms : ms
secShow = (sec<10) ? "0" + sec : sec
minShow = (min<10) ? "0" + min : min
document.getElementById("numbers").innerHTML = minShow + ":" + secShow + ":" + msShow
}
var swTimer
function goFunction() {
swTimer = setInterval(addTime, 10)
}
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
<div class = "controls">
<button onclick="goFunction()" class="button button1">GO</button>
<button onclick="resetFunction()" class="button button2">RESET</button>
<button onclick="stopFunction()" class="button button3">STOP</button>
<div class="display" id = "numbers">00:00:00</div>
</div>

Related

Add EXPIRATION message to JS countdown timer

I have following script:
document.getElementById("timer").innerHTML = 0 + ":" + 10;
function startTimer() {
var presentTime = document.getElementById("timer").innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond(timeArray[1] - 1);
if (s == 59) {
m = m - 1;
}
if (m < 0) {
return;
}
document.getElementById("timer").innerHTML = m + ":" + s;
console.log(m);
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec;
} // add zero in front of numbers < 10
if (sec < 0) {
sec = "59";
}
return sec;
}
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
All works great, but when timer expires it just shows "0:00"
How can I add expiration message inside ?
Thank you!
You can add your message expiry message, inside the minute expiry if block if (m<0){} before the return statement. I added the solution to your code below for reference
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<script>
document.getElementById('timer').innerHTML =
0 + ":" + 3;
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
document.getElementById('timer').innerHTML = "Timer expired."
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
startTimer();
</script>
</body>
</html>
the problem is that you want to console.log(m) which is just 0:00. I've changed a bit of your code so instead of m it logs n which is: n = m + ":" + s;
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<script>
document.getElementById('timer').innerHTML =
0 + ":" + 10;
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
}
document.getElementById('timer').innerHTML =
n = m + ":" + s;
console.log(n)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
</script>
try it like this
var timeleft = 11;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
alert("Timer Expired!")
return;
}
document.getElementById("progressBar").value = timeleft - 1;
document.getElementById("timer").innerHTML = "0:"+(timeleft - 1);
timeleft -= 1;
}, 1000);
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<progress value="0" max="10" id="progressBar"></progress>

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>

How can i get the seconds to reset to 0 when they reach 60

Hi there I have a stopwatch embedded in my website, however I have a problem. When the seconds reach 60 therefore 1 minute they should reset to 00. However in this case while the minute will increase every 60 seconds the seconds will not reset to zero. Here is my code
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10);
if (secs <= 9) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
Any help much appreciated
You can use that code
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10);
if(secs >= 60)
{
secs = secs - ( mins * 60 );
}
if ((secs).toString().length === 1) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if ((tenths).toString().length === 1) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
Just include a modulo by 60 to line number 36 to properly reset seconds to 0 (line commented to highlight):
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10) % 60; // <-- see here for change
if (secs <= 9) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>

How to Run the time that the timezone is Denmark Copenhagen

I found the code which is can run my stopwatch. but iwant to follow denmark country timezone to run my code. how to d
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, hiden, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).val());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
$(hiden).val(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed","#stoppedid", 1);
timeLogger.start();
$("#confirm").click(function() { //Stop timer upon clicking the Confirm Button
timeLogger.stop();
});
});
</script>
Thank you in advance.
I cant post another question thats why i need to edit may other questions
remove disabled property of input[name=stwa] and add readonly property for there
Use navigator.cookie to save time on javascript
Here is your solutions
if(localStorage.getItem("sec"))
{
var sec = localStorage.getItem("sec");
var min = localStorage.getItem("min");
var hour = localStorage.getItem("hour");
stopwatch("Start");
}else{
var sec = 0;
var min = 0;
var hour = 0;
}
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
localStorage.setItem("sec", sec);
localStorage.setItem("min", min);
localStorage.setItem("hour", hour);
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Start "; }
if (text == "Stop ") { document.clock.theButton.value = "Stop"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
localStorage.clear();
}
<form name="clock" action="save_time_log.php" method="post">
<div class="form-group">
<input type="text" class="form-control time_tracker" disabled name="stwa" placeholder="00:00:00">
</div>
<input type="button" name="theButton" onClick="stopwatch(this.value);" class="btn btn-block btn-default btn-flat" value="Start" />
<input type="submit" name="stops" value="Stop" onClick="stop();" class="btn btn-block btn-default btn-flat"/>
</form>

Timer work in javascript

In my project i am using timer which runs, when start button is clicked and stop when end is clicked
The problem is by mistake when start button is clicked double or more than once ..time takes +1000 millsec extra and start running faster ..this should no happen
My javascript is..
<script type="text/javascript">
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1;
} else {
min = min;
}
if (min == 60) {
min = 0;
hour += 1;
}
if (sec<=9) { sec = "0" + sec; }
document.getElementById("starttime").innerHTML = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
SD=window.setTimeout("stopwatch();", 1000);
}
function f3() {
clearTimeout(SD);
}
</script>
<form name="clock">
<div id="starttime" style="font-size:large; "></div>
<input type="button" name="theButton" id="Start" value="Start" onClick="stopwatch(this.value);" />
<input type="button" name="theButton" id="end" value="Stop" onClick="f3();" />
</form>
I have tried something like this..
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true; }`
.... but its not working
Don't call stopwatch() directly.
Call something else which checks SDs state, and then calls stopwatch().
<input type="button" name="theButton" id="Start" value="Start" onClick="startStopWatch();" />
var sec = 0;
var min = 0;
var hour = 0;
var SD;
function startStopWatch(){
if (!SD){
stopwatch();
}
}
function stopwatch() {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
if (sec<=9) { sec = "0" + sec; }
document.getElementById("starttime").innerHTML = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
SD=window.setTimeout(stopwatch, 1000);
}
function f3() {
if (SD){
clearTimeout(SD);
}
}
Live Demo: http://jsfiddle.net/uJPff/2
You can do something like this:
var SD;
function stopwatch(text) {
if (SD && text) {
return;
}
....
}
function f3() {
clearTimeout(SD);
SD = false;
sec = 0;
min = 0;
hour = 0;
}
I.e. you can check, if the timeout is already running when the button is clicked and cancel the execution, if needed.
You can test it at updated jsFiddle.

Categories