How to toggle or pause setInterval in javascript - javascript

I am learning java Script and i am trying to create clock which should be "when I click the button, the time Should stop changing and the button Should change from “Stop time” to “Start time” & when I click the button again, the time should begin changing and the button should change from “Start time” to “Stop time”. See my codes and tell me which codes or function i need to add and where to add... I am newbie in it so i will appreciate your help..
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
</body>
</html>
//---Script Here---
<script>
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
</script>

Try this one
let currentTime = new Date();
let status = true;
let interval = 1; // in seconds
let dateFormat = { hour: 'numeric', minute:'numeric', second: 'numeric', hour12: true };
let clock = document.querySelector('#demo');
clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
let timer = setInterval(
function () {
currentTime.setSeconds(currentTime.getSeconds() + interval);
clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
}, interval * 1000
);
let button = document.querySelector('#button');
button.addEventListener('click', onClick);
function onClick() {
if (!status) {
button.innerHTML = 'Stop timer';
timer = setInterval(
function () {
currentTime.setSeconds(currentTime.getSeconds() + interval);
clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
}, interval * 1000
);
return;
}
if (status) {
button.innerHTML = 'Start timer';
clearInterval(timer);
}
status = !status;
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button id="button">Stop time</button>

You just need a little trick to toggle the function here you are:
var myVar = setInterval(function () {
myTimer()
}, 1000);
var isPaused = false;
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function toggleFunction() {
if (isPaused) {
myVar = setInterval(function () {
myTimer()
}, 1000);
isPaused = false;
} else {
clearInterval(myVar);
isPaused = true;
}
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="toggleFunction()">Toggle time</button>

let time = document.getElementById("time");
let stopButton = document.getElementById("stop");
let timeCount = 0,
currentTimeout;
function play() {
stopButton.hidden = false;
clearInterval(currentTimeout);
currentTimeout = setInterval(() => {
timeCount++;
const min = String(Math.trunc(timeCount / 60)).padStart(2, 0);
const sec = String(Math.trunc(timeCount % 60)).padStart(2, 0);
time.innerHTML = `${min} : ${sec}`;
}, 1000);
}
function pause() {
clearInterval(currentTimeout);
}
function stop() {
stopButton.hidden = true;
pause();
timeCount = 0;
time.innerHTML = `00 : 00`;
}
<div>
<h1 id="time">00 : 00</h1>
<br />
<div>
<button onclick="play()">play</button>
<button onclick="pause()">pause</button>
<button onclick="stop()" id="stop" hidden>Reset</button>
</div>
</div>

Related

Why is my JavaScript second counter not working?

I made a second counter in JavaScript. But my code is not working.
My problem: "First I pressed Start button, but seconds was not going on normally."
Here is my codes:
var a = 0;
var Time = setInterval(Counter, 1000);
function startCounter() {
setInterval(Counter, 1000);
}
function Counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(Time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<button onclick="startCounter()">Start</button>
<br>
<button onclick="pauseCounter()">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button onclick="resetCounter()">Reset</button>
The problem in your code is following line:
setInterval(Counter, 1000);
In above line you are creating an interval but you are not assigning it to any variable. So its not being cancelled.
Before starting a new interval make sure to clear the last one.
You need to assign the new setInterval to Time each time
var a = 0;
var Time;
function startCounter() {
clearInterval(Time)
Time = setInterval(Counter, 1000);
}
function Counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(Time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<button onclick="startCounter()">Start</button>
<br>
<button onclick="pauseCounter()">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button onclick="resetCounter()">Reset</button>
When you defined Time, you set it as an interval preemptively, meaning that it starts instantly. And in startCounter(), you just created an unnamed interval, which you cannot clear.
var a = 0;
var Time;
function startCounter() {
clearInterval(Time) // prevent multiple intervals at same time
Time = setInterval(Counter, 1000);
}
function Counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(Time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<body>
<script src="index.js"></script>
<button onclick="startCounter()">Start</button>
<br>
<button onclick="pauseCounter()">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button onclick="resetCounter()">Reset</button>
</body>
You need to clear the interval but also use type=button and addEventListener
let a = 0;
let time;
let seconds;
window.addEventListener("load", function() {
seconds = document.getElementById("seconds");
document.getElementById("start").addEventListener("click", function() {
clearInterval(time);
time = setInterval(counter, 1000);
});
document.getElementById("pause").addEventListener("click", pauseCounter);
document.getElementById("resetBut").addEventListener("click", resetCounter);
});
function counter() {
a += 1;
seconds.innerHTML = a;
}
function pauseCounter() {
clearInterval(time);
}
function resetCounter() {
a = 0;
seconds.innerHTML = a;
}
<button type="button" id="start">Start</button>
<br>
<button type="button" id="pause">Pause</button>
<p>Seconds: <a id='seconds'>0</a></p>
<button type="button" id="resetBut">Reset</button>
You have to set the seconds object like this.
seconds = document.getElementById('seconds')

How to store count-up timer in JavaScript as users navigate to separate routes in the web-page

I am trying to build a web-page that allows you to start a count-up timer when you click the start button and allows you to navigate to different route on the web-page start another timer and the navigate back to the first page and have the timer still running. Currently I have the and button functionality working. However, I am not sure how to get the clock not to reset. when I navigate to another page. This The web-page is mostly written wit Python and Flask, But I am using JavaScript for the time functionality. This is the only JavaScript I have worked with and most of it comes from other posts.
<div id=time>
<div><span id="hour"></span>:<span id="minute"></span>:<span id="seconds"></span></div>
<button id="start-btn">Start</button>
<button id="stop-btn">Pause</button>
<button id="reset-btn">Reset</button>
</div>
<script>
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;
let intervalId = null;
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds /3600);
minute = Math.floor((totalSeconds - hour*3600)/60);
seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("hour").innerHTML =hour;
document.getElementById("minute").innerHTML =minute;
document.getElementById("seconds").innerHTML =seconds;
}
document.getElementById('start-btn').addEventListener('click', () => {
intervalId = setInterval(startTimer, 1000);
})
document.getElementById('stop-btn').addEventListener('click', () => {
if (intervalId)
clearInterval(intervalId);
});
document.getElementById('reset-btn').addEventListener('click', () => {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
});
</script>
If you want to prevent that your timer got reseted, use a cookie to store the date when the timer started.
Do not increase your timer every second, but instead subtract the current time with the time when the timer started.
<!DOCTYPE html>
<html>
<head>
<title>Timer test</title>
</head>
<body>
<div id="time">
<div><span id="hour"></span>:<span id="minute"></span>:<span id="seconds"></span></div>
<button id="start-btn">Start</button>
<button id="stop-btn">Pause</button>
<button id="reset-btn">Reset</button>
</div>
<script type="text/javascript">
let hour = 0;
let minute = 0;
let seconds = 0;
let pauseTime = null;
let start = [...document.cookie.matchAll(/([^;=]+)=([^;=]+)(;|$)/g)].filter(x => x[1].trim() == 'timer').map(x => Number(x[2].trim()))[0];
if(start != null) {
if(start > 0) start = new Date(start);
else if(start < 0) {
pauseTime = -start;
start = new Date(Date.now() + start); //+- = -
} else start = null;
} else start = null;
let intervalId = null;
function startTimer() {
let totalSeconds;
if(pauseTime) {
start = new Date(Date.now() - pauseTime);
totalSeconds = pauseTime;
return;
} else {
totalSeconds = Math.floor((Date.now() - start.getTime()) / 1000);
}
hour = Math.floor(totalSeconds /3600);
minute = Math.floor((totalSeconds - hour*3600)/60);
seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("hour").innerHTML =hour;
document.getElementById("minute").innerHTML =minute;
document.getElementById("seconds").innerHTML =seconds;
}
if(start) intervalId = setInterval(startTimer, 1000);
document.getElementById('start-btn').addEventListener('click', () => {
if(pauseTime) {
pauseTime = null;
} else {
if(start) return;
start = new Date();
intervalId = setInterval(startTimer, 1000);
}
document.cookie = "timer=" + String(start.getTime());
})
document.getElementById('stop-btn').addEventListener('click', () => {
pauseTime = Date.now() - start.getTime();
document.cookie = "timer=" + String(-pauseTime);
});
document.getElementById('reset-btn').addEventListener('click', () => {
start = null;
document.cookie = "timer=null";
if(intervalId) clearInterval(intervalId);
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
});
</script>
</div>
</body>
</html>

Stopwatch in JavaScript

Before marking the question duplicate, I want to tell that I have been through all the stopwatch and JavaScript searches but as I am new to the JavaScript, so I can not come to the possible solution myself and I need the help from you guys.
What I want to achieve is to start and stop the watch with the same button. I can stop the watch but can not start again, can't figure out why.
Have a look at the following script and correct me.
var startTimer = setInterval(function(){myTimer()}, 1000);
function myTimer(){
var current = new Date();
document.getElementById("timer").innerHTML = current.toLocaleTimeString();
}
function start(st){
// Problem is in this statement
// How can I call the global function variable again that's startTimer
window[st]();
var elem = document.getElementById("myButton");
elem.innerHTML = "Stop";
elem.addEventListener("click", stop);
}
function stop(){
clearInterval(startTimer);
var elem = document.getElementById("myButton");
elem.innerHTML = "Start";
elem.addEventListener("click", start(startTimer));
}
<p id="timer"></p>
<button id="myButton" onclick="stop(startTimer)">Stop</button>
You want a single method to take care of the start/stop:
var startTimer = setInterval(myTimer, 1000),
timerElement = document.getElementById("timer"),
buttonElement = document.getElementById("myButton");
function myTimer(){
var current = new Date();
timerElement.innerHTML = current.toLocaleTimeString();
}
function toggle(){
if (startTimer) {
clearInterval(startTimer);
startTimer = null;
buttonElement.innerHTML = "Start";
} else {
buttonElement.innerHTML = "Stop";
startTimer = setInterval(myTimer, 1000);
}
}
<p id="timer"></p>
<button id="myButton" onclick="toggle()">Stop</button>
Why clearing your interval?
catch-up where the interval left.
var timer = document.getElementById("timer"),
paused = 0;
setInterval(function(){
if(!paused) timer.innerHTML = new Date().toLocaleTimeString();
}, 1000);
document.getElementById("myButton").addEventListener("click", function(){
this.innerHTML = (paused ^= 1) ? "Start" : "Stop";
});
<p id="timer"></p>
<button id="myButton">Stop</button>
P.S: Always cache elements you plan to reuse, specially if inside an interval fn.
(paused ^= 1) is used to toggle ones and zeroes 1,0,1,0,1... used than as boolean.

stopwatch in javascript using new Date object

In script below i try to make some kind of stopwatch:
<html>
<head>
<script>
var t; var time; var timetoRun=180000;// 3 min
function Timer()
{
stoper = (this.startTime+ this.timetoRun)-new Date().getTime();
x = parseInt(stoper / 1000);
s = x % 60;
x = parseInt(x/60);
m = x % 60;
if (s<10) s='0'+ s;document.getElementById('txt').innerHTML=m+':'+s;
this.t=setTimeout(function(){Timer()},500);
}
function myStopFunction(){clearTimeout(t);}
function init(){this.startTime = new Date().getTime();}
</script>
</head>
<body onload="init()">
<div id="txt"></div>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="Timer()">Start time</button>
</body>
</html>
The problem is : when i stop time at 2:28 and start it again after 5 sec. value jump at once to 2:23 . What i want to achieve is: stop time at (for example) 2:31 and run it again from 2:31.
Thanks in advance.
You could simplify a lot your code so to avoid the use of a Date object.
Furthermore you have forgot some var keyword and a condition to stop your timer when the time has run out. I've also inserted a resetTimer method so if you need to restart the timer twice or more, it will be set to 180 seconds again
Example codepen : http://codepen.io/anon/pen/Duier
Code
var
// seconds
timetoRun,
// cache a reference to the DOM element in which you update the timer
timeElement,
// your interval
intv;
function Timer() {
var ss = timetoRun % 60;
var mm = (timetoRun / 60) | 0; // Math.floor
if (ss < 10) ss = '0' + ss;
timeElement.innerHTML = [mm,ss].join(":");
if (timetoRun-- > 0) {
intv = setTimeout(Timer, 1000);
}
else {
myStopFunction();
resetTimer();
}
};
function myStopFunction() { clearInterval(intv); };
function resetTimer() {
timetoRun = 180 //second;
};
function init() {
resetTimer();
timeElement = document.getElementById('txt');
};
I think this is the solution you are looking for
<html>
<head>
<script>
var t;
var time;
var timetoRun=180000;// 3 min
var lastTime = -1;
function StartTimer() {
this.startTime = new Date().getTime();
this.lastTime = lastTime < 0 ? this.timetoRun : this.lastTime;
this.timetoRun = this.lastTime;
Timer();
};
function Timer() {
var difference = (this.startTime - new Date().getTime());
console.log(difference / 1000);
this.lastTime = this.timetoRun + difference;
x = parseInt(this.lastTime / 1000);
s = x % 60;
x = parseInt(x/60);
m = x % 60;
if (s<10) s='0'+ s;
document.getElementById('txt').innerHTML=m+':'+s;
this.t=setTimeout(function(){
Timer();
},500);
}
function myStopFunction() {
clearTimeout(t);
};
</script>
</head>
<body>
<div id="txt"></div>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="StartTimer()">Start time</button>
</body>
</html>
or you can try it here
http://plnkr.co/edit/ySOGRCvnPILNTinCriCL?p=preview
I think you have really over complicated things here the simpler way would be to do something like this http://jsfiddle.net/4Ey9Z/2/
var timetoRun=180000; var timer, elem = document.getElementById('txt');
function startTime(){
timer= setInterval(function(){CountDown()},1000);
}
function stopTime(){
clearInterval(timer);
}
function CountDown(){
var seconds = parseInt((timetoRun/1000)%60,0)
, minutes = parseInt((timetoRun/(1000*60))%60,0);
timetoRun = timetoRun - 1000;
elem.innerHTML=minutes+':'+seconds;
if((seconds===0)&&(minutes ===0)){
stopTime();
}
}

How to start a clock again with setInterval() after I stopped it

I can stop it but how would I make it start again at the current time on the start function? Why doesn't this work?
<!DOCTYPE>
<html>
<head>
</head>
<body>
<p id="demo"></p>
<button onclick="stopFunction()">Stop time</button>
<button onclick="startFunction()">Start time</button>
</body>
</html>
JavaScript:
var myVar = setInterval(function () {
myTimer();
}, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function stopFunction() {
clearInterval(myVar);
}
function startFunction() {
document.getElementById("demo").innerHTML = t;
}
edit: I threw in some code to disable the start button when it's running. It's a good idea to do this, or else write some logic in to not keep calling setInterval every time it's clicked/running
<!DOCTYPE>
<html>
<head>
</head>
<body>
<p id="demo"></p>
<button id='stopButton' onclick="stopFunction()">Stop time</button>
<button id='startButton' onclick="startFunction()">Start time</button>
<script type='text/javascript'>
var myVar;
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function stopFunction() {
clearInterval(myVar);
document.getElementById("startButton").disabled = false;
}
function startFunction() {
myVar = setInterval(myTimer, 1000);
document.getElementById("startButton").disabled = true;
}
startFunction();
</script>
</body>
</html>
Change it to this:
var t = d.toLocaleTimeString();
function myTimer()
{
var d;
d = new Date();
t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
var myVar = setInterval(myTimer, 1000);
function stopFunction()
{
clearInterval(myVar);
}
function startFunction()
{
document.getElementById("demo").innerHTML = t;
//Restart it here
myVar = setInterval(myTimer, 1000);
}
The problem was that you were not starting the interval again. This now does that.

Categories

Resources