Stopwatch in JavaScript - 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.

Related

interval starting two times

When the user clicks a button an interval will start counting but the problem is that if the user clicks the button two times there will be two intervals I tried clearInterval(interval);
before assigning the interval but the timer stopped counting.
function times(){
var element=document.getElementById("sec");
counter=0;
let interval= setInterval(myFunction, 1000);
function myFunction(){
counter++;
element.innerHTML=counter;
}
}
document.querySelector('#sec').addEventListener('click', function() {
times();
})
let interval;
let counter = 0;
function times() {
clearInterval(interval);
interval = setInterval(myFunction, 1000);
counter = 0;
}
function myFunction() {
var element = document.getElementById("sec");
counter++;
element.innerHTML = counter;
console.log(counter);
}
<button id="sec">timer</button>
if to want to clear the previously set interval when ever the user clicks, Just store the interval ID in a higher scope and clear the interval the previously set interval before creating a new one.
let interval
function times(){
clearInterval(interval);
var element=document.getElementById("sec");
counter=0;
interval = setInterval(myFunction, 1000);
function myFunction(){
counter++;
element.innerHTML=counter;
}
}
You may try the following. Depending on the existence of the interval it is decided whether to (re-)start the timer or stop it.
let interval
function times(){
var element=document.getElementById("sec");
counter=0;
if (interval) {
clearInterval(interval)
interval = null
} else {
function myFunction(){
counter++;
element.innerHTML=counter;
}
element.innerHTML=counter; // just to show '0' when re-starting
interval= setInterval(myFunction, 1000);
}
}
<button onclick="times()">Start / Stop</button>
<span id="sec">0</span>

Reset function by button

I have a button that disappears by a function after one second.
if I click on the button, I want the function will reset and I will get one another second to click. And-I want the button will disappeared if I did not click this second.
(if I click in a second, the button doesn't disappeared, if I miss one second, it is disappeared, but if I click, I'll get another second, and so on...)
This is my code:
HTML:
<button id="btn">click
</button>
JavaScript:
let btn = document.querySelector('#btn');
btn.addEventListener('click', ()=>{
click();
})
setTimeout(function click() {
btn.style.display = ('none');
}, 1000);
That code doesn't work.
I am an absolute beginner, so any feedback will help me.
If my question is not understood, please write to me in the comments or edit the question.
This is my suggestion:
var c = 10;
var timer;
clock();
function clock() {
timer = setInterval(countdown, 1000);
}
function countdown() {
counter.innerHTML = --c;
if (c === 0) {
btn.style.display = 'none';
clearInterval(timer);
}
}
btn.onclick = function() {
clearInterval(timer);
c = 10;
counter.innerHTML = c;
clock();
};
<button id="btn">Click me before it's too late (<span id="counter">10</span>)</button>
Change your javascript to the following:
let btn = document.querySelector('#btn');
btn.addEventListener('click', ()=>{
click();
})
function click() {
setTimeout(function() {
btn.style.display = 'none';
}, 1000);
}
Click was not defined properly :)
You should try jQuery, it'll make your learning a lot easier!
Also press f12 on Google Chrome to show developer console, errors will show up there.
You need to apply the display:none inside setTimeout. Here is an example.
let btn = document.querySelector('#btn');
let time = document.querySelector('#time');
const timeLimit = 10;
let timeoutId, intervalId;
time.innerText = timeLimit;
let startTime;
window.onload = () => {
startTime = Date.now();
startTimer();
removeButton();
}
btn.addEventListener('click', stop);
function stop() {
intervalId && clearInterval(intervalId);
timeoutId && clearTimeout(timeoutId);
}
function startTimer() {
let count = 1;
intervalId = setInterval(() => {
if(count === 10) clearInterval(intervalId);
time.innerText = timeLimit - count;
count++;
}, 1000);
}
function removeButton() {
timeoutId = setTimeout(() => {
btn.style.display = 'none';
}, timeLimit*1000);
}
<button id="btn">Click me. I am disappearing ⏳ <span id="time"></span></button>

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>

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

Pausing a stopwatch does not stop the time

Hopefully I can make myself clear here.
I am using the following code to run my stopwatch:
function timecounter(starttime)
{
currentdate = new Date();
details = document.getElementById('details');
stopwatch = document.getElementById('stopwatch');
var timediff = currentdate.getTime() - starttime;
if(runningstate == 0)
{
timediff = timediff + stoptime
}
if(runningstate == 1)
{
stopwatch.value = formattedtime(timediff);
refresh = setTimeout('timecounter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function startandstop()
{
var startandstop = document.getElementById('startandstopbutton');
if(runningstate==0)
{
startandstop.value = 'Pause';
runningstate = 1;
timecounter(starttime);
}
else
{
startandstop.value = 'Start';
runningstate = 0;
lapdate = '';
}
}
But when I select the button to pause the time, the time stops, but when I press start again, it jumps to the time that it currently is as if I had not pause the time.
I have been trying to figure out what's going on with it and have come to no success.
I believe that it might have something to do with the timecounter() function but from there I am not certain.
Any help would be greatly appreciated!
Thanks,
Brandon
I think you should use .performance.now() if you want something close to accurate in terms of ms.
Thought you had an interesting problem so I came up with a solution of my own for fun. Hope it helps. :) (UPDATES BELOW THE CODE)
http://jsfiddle.net/colbycallahan/CjDz7/1/ (cleaned it up a bit for display and rounding a bit)
Works and Requires jQuery:
HTML:
<div id="console"></div>
<input type="button" id="btn" value="start time">
<input type="button" id="btn2" value="stop time">
js:
var timerRunning = false;
var startTime;
var totalTime;
$('#console').data('totalTime', 0);
function startTimer(){
totalTime = $('#console').data('totalTime');
startTime = window.performance.now();
timerRunning = true;
function timerLoop(){
window.setTimeout(function(){
if(timerRunning){
$('#console').text(window.performance.now() - startTime + totalTime);
timerLoop();
}
}, 50);
}
timerLoop();
}
$('#btn').on('click', function(){
startTimer();
});
$('#btn2').on('click', function(){
totalTime = window.performance.now() - startTime + totalTime;
$('#console').data('totalTime', totalTime);
timerRunning = false;
});
I took your code and the first thing I did was fix what can possibly cause errors in terms of syntax regarding curly braces on separate lines from if statement, missing semicolon in the if statement for when running state is 0, one semicolon incorrectly placed in timecounter() call. You tried to call a function by making it a string, but strings never call functions. starttime is not defined before you pass it as an argument to timecounter(). Your settimeout() line should be set up outside the condition statement to call it. You unnecessarily call an else if running state is not 1. lapdate is not defined other than to make it empty string. Also refresh is not defined unless running state is 1, but is only called when refresh does not equal 1. Lastly you did not include all of the code necessary to know if additional mistakes were made nor is there enough code to know if what I rewrote will fix your issue, which is why I wrote new code(it requires jquery library to be included on your page). I don't really understand the logic of your code. One more thing: you will need to retrieve the stored value of elapsed time after a user has started timer, clicked pause, and then resumed the timer. As a thanks, you should go to JSLint.com or similar and never run your code in a browser until it passes a lint test. I am only reposting your code at the bottom and don't expect it to work. I redid my timer in vanilla javascript with no jquery required. It is here:
Works and Requires no jQuery:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="console"></div>
<input type="button" id="btn" value="start time" onclick="startTimer();">
<input type="button" id="btn2" value="stop time" onclick="stopTimer();">
<input type="hidden" id="storedTime" value="0">
<script>
var timerRunning = false;
var startTime;
var totalTime;
var storedTimeInp = document.getElementById('storedTime');
var console = document.getElementById('console');
function startTimer(){
totalTime = Number(storedTimeInp.value, 10);
startTime = window.performance.now();
timerRunning = true;
function timerLoop(){
window.setTimeout(function(){
if(timerRunning){
console.innerHTML = (window.performance.now() - startTime + totalTime);
timerLoop();
}
}, 50);
}
timerLoop();
}
function stopTimer(){
totalTime = window.performance.now() - startTime + totalTime;
storedTimeInp.value = totalTime;
timerRunning = false;
}
</script>
</body>
</html>
Your Code Rewritten Kinda(broken):
var runningstate = 0;
function timecounter(starttime){
currentdate = new Date();
details = document.getElementById('details');
stopwatch = document.getElementById('stopwatch');
var timediff = currentdate.getTime() - starttime;
setTimeout(
if(runningstate == 0){
timediff = timediff + stoptime;
}else{
stopwatch.value = formattedtime(timediff);
timecounter(starttime);
stoptime = timediff;
}
,10);
}
function startandstop(){
var startandstop = document.getElementById('startandstopbutton');
if(runningstate==0){
startandstop.value = 'Pause';
runningstate = 1;
starttime = new Date();
starttime = starttime.getTime();
timecounter(starttime);
}else{
startandstop.value = 'Start';
runningstate = 0;
lapdate = '';
}
}

Categories

Resources