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

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.

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 toggle or pause setInterval in 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>

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.

increment value of a number with a specific timer-value

I've tried and looked around but I could not find anything similar.
<div> <span>23</span>/ 30 </div>
My thought process here is that I want 23 to increment in 1 value every 15th second.
And when it hits 30, it shall stop counting. I have no idea how to make it "stop" counting and how I should approach a problem like this.
Any help would be much appreciated!
Here is a possible solution, note that I do an iteration every second for the demo, but you can lower the rate by doing setTimeout(count,15000);.
var wrapper, value, timer;
window.addEventListener('load', startCounter, false);
function startCounter(){
document.querySelector('button').onclick = startCounter;
wrapper = document.querySelector('span');
value = 22;
count();
}
function count(){
clearTimeout(timer);
value++;
wrapper.innerHTML = value;
if(value < 30){ timer = setTimeout(count,1000); }
}
<div> <span>23</span>/ 30 </div>
<button>reset</button>
<div id="show"></div>
<script>
function timer(){
var i = 0;
setInterval(function(){
i++;
document.getElementById("show").innerHTML = i;
if(i > 30){
i = 0;
}
},1000);
}
timer();
</script>
//just super simple hope can be inspiration done thank
If a class is added to the span element like so:
<div> <span class="counter">23</span>/ 30 </div>
Then this javascript code would work:
var currentCount = parseInt($('.counter').text());
var increaseCount = function() {
if (currentCount < 30) {
currentCount = currentCount + 1;
$('.counter').text(currentCount);
setTimeout(increaseCount, 15000);
}
return;
};
setTimeout(increaseCount, 15000);
Here is an example with the timer set to a second:
https://jsfiddle.net/aqe43oLa/1/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var i = 24;
var timer=setInterval( increment, 15000);
function increment(){
if(i<=30)
{
console.log(i);
$('.increase').html('').append(i);
i++;
}
else
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<div><span class="increase">23</span>/ 30 </div>
</body>
</html>

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

Categories

Resources