stopwatch in javascript using new Date object - javascript

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

Related

how to create click event to display set interval time

I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}
This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>
First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)

Javascript stopwatch with millisecond increments

I am trying to put together a stopwatch using JavaScript. I have got the date to populate with the correct information but my Stopwatch doesn't work. I click start and the numbers never move from 0, I would like to have it increment in MS no seconds. I have my code for the JS and the HTML also. HTML is functioning as it should but the JS is not. I am very green to the JavaScript world and i have looked and looked and was unable to come across a solution that would be a benefit to me. Thanks for your assistance.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var stopwatchTimer;
var elapsedMinutes = 0;
var elapsedSeconds = 0;
var elapsedMilliseconds = 0;
var displayCurrentTime = function() {
var now = new Date();
var hours = now.getHours();
var ampm = "AM";
if (hours > 12) {
hours = hours - 12;
ampm = "PM";
} else {
switch (hours) {
case 12:
ampm = "PM";
break;
case 0:
hours = 12;
ampm = "AM";
}
}
$("hours").firstChild.nodeValue = hours;
$("minutes").firstChild.nodeValue = padSingleDigit(now.getMinutes());
$("seconds").firstChild.nodeValue = padSingleDigit(now.getSeconds());
$("ampm").firstChild.nodeValue = ampm;
};
var padSingleDigit = function(num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
var tickStopwatch = function() {
// I also need to increment in 10 milliseconds increments but unsure if I //have this right
var ms=0;
var sec=0;
var min=0;
var frame= function() {
If(ms==1000)
ms=0;
sec++;
}
if(sec==60) {
sec=0;
min++;
document.getElementById("s_seconds").innerHTML = valueOf(sec);
document.getElementById("s_minutes").innerHTML = valueOf(min);
document.getElementById("s_ms").innerHTML = valueOf(ms);
}
};
var startStopwatch = function(evt) {
};
var stopStopwatch = function(evt) {
};
var resetStopwatch = function(evt) {
};
window.onload = function() {
displayCurrentTime();
setInterval(tickStopwatch, 1000);
};
"use strict"; //evt is in a separate file
var evt = {
attach: function(node, eventName, func) {
},
detach: function(node, eventName, func) {
},
preventDefault: function(e) {
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="library_event.js"></script>
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock with stopwatch</h1>
<fieldset>
<legend>Clock</legend>
<span id="hours"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
<fieldset>
<legend>Stop Watch</legend>
Start
Stop
Reset
<span id="s_minutes">00</span>:
<span id="s_seconds">00</span>:
<span id="s_ms">000</span>
</fieldset>
</main>
</body>
</html>
If you incrementally update the values ms, seconds, minutes you'll never be accurate. You'll lose time with every update. There simply is no interval that can operate at that speed and accuracy in JS.
Instead, compute them from the internal clock
let offset = 0,
paused = true;
render();
function startStopwatch(evt) {
if (paused) {
paused = false;
offset -= Date.now();
render();
}
}
function stopStopwatch(evt) {
if (!paused) {
paused = true;
offset += Date.now();
}
}
function resetStopwatch(evt) {
if (paused) {
offset = 0;
render();
} else {
offset = -Date.now();
}
}
function format(value, scale, modulo, padding) {
value = Math.floor(value / scale) % modulo;
return value.toString().padStart(padding, 0);
}
function render() {
var value = paused ? offset : Date.now() + offset;
document.querySelector('#s_ms').textContent = format(value, 1, 1000, 3);
document.querySelector('#s_seconds').textContent = format(value, 1000, 60, 2);
document.querySelector('#s_minutes').textContent = format(value, 60000, 60, 2);
if(!paused) {
requestAnimationFrame(render);
}
}
<fieldset>
<legend>Stop Watch</legend>
Start
Stop
Reset
<span id="s_minutes">00</span>:
<span id="s_seconds">00</span>:
<span id="s_ms">000</span>
</fieldset>
offset stores two values: when paused it stores the value at which you stopped, otherwise it stores the offset you have to add to Date.now() to compute the value.
The value is the time in ms, computing seconds and minutes out of it is basic arithmetic.
Your interval function is set to run once per 1000ms (or 1 sec), which won't give you 1ms resolution. In fact, the best you can do is 10ms resolution with setInterval. You also need to increment a counter, which you currently don't do.
Try:
setInterval(tickStopwatch, 10);
var ms = 0;
var tickStopwatch = function() {
var ms += 10;
// rest of your logic
}

What is wrong with countdown timer program?

I'm trying to make a countdown timer to go from 15 minutes 0 seconds to 0 minutes 0 seconds but it appears that it doesn't want to display in JsFiddle. Another program is that my date variable isn't actually set to 15 minutes and 0 seconds. How can I fix this?
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
var handler = function() {
sec--;
if (sec == 60) {
sec = 0;
min--;
else if (sec < 0) {
date.setSeconds(0);
} else if (min < 0) {
date.setMinutes(0);
}
}
document.getElementById("time").innerHTML = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
handler();
setInterval(handler, 1000);
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: center"></h1>
Well, for one thing, you don't have a closing brace before the else, so it won't even run as is.
In addition, I'm not sure why you need to fiddle around with date objects for a countdown timer, since the current date/time is irrelevant.
You should start with something like:
function pad2(s) {
return ("00" + s).slice(-2);
}
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};
var sec = 1;
var min = 15;
handler();
setInterval(handler, 1000);
You'll notice I've refactored out the padding code since it's "questionable" whether you should ever violate the DRY principle. You certainly shouldn't violate it twice on a single line :-)
In terms of testing, you can create a simple static page which runs the timer as follows.
I've also reduced starting time to a little over ten minutes and accelerated time ten-fold so you don't have to wait around for a full quarter hour to test the whole thing (it should take a smidgen more than a minute to complete).
<html>
<body>
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: left"></h1>
<script type="text/javascript">
function pad2(s) {
return ("00" + s).slice(-2);
}
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = sec = 0;
}
}
document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};
var sec = 6;
var min = 10;
handler();
setInterval(handler, 100); // 10x normal speed, use 1000 for reality
</script>
</body>
</html>
For starters, you do not have a closing brace before the else if and you need to remove the brace before your document.getElementById
1) Closed your curly-bracket for your if condition.
2) Your code failed to load properly because your JavaScript loads before the page recognizes the time DIV element. Since you didn't use an event listener for the page loading first, I added that... and it seems to be working.
3) Important note... The timer logic needs a lot of work... You're better off using a time DIFF statement otherwise you've got about 200-300 lines more to write just on calculating seconds, minutes, hours, days etc.
Looking at the page as it stands has this... 15:0-289
** Update ** adding the padding technique rectified the above note...
Here's a solution for that.
Check time difference in Javascript
<html>
<head>
<script type="text/javascript">
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
document.addEventListener("DOMContentLoaded", function(event) {
var myTimer = setInterval(handler, 1000);
});
function pad2(s) {
return ("00" + s).slice(-2);
}
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
document.getElementById("time").innerHTML = pad2(min) + ":" + pad2(sec);
};
</script>
</head>
<body>
<b>Offer Ends In:</b>
<h1 id="time" style="text-align: center"></h1>
</body>
</html>
I just made this StopWatch. You can use it without a button and it will work like you want.
//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, T, MillisecondConverter, StopWatch; // for use on other loads
addEventListener('load', function(){
var doc = document, bod = doc.body, htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
T = function(tag){
return doc.getElementsByTagName(tag);
}
MillisecondConverter = function(milliseconds, displayMilliseconds){
var ms = milliseconds, rh = ms/3600000, hp = Math.pow(10, rh.toString().length-2);
this.hours = Math.floor(rh);
var rm = (rh*hp-this.hours*hp)/hp*60, mp = Math.pow(10, rm.toString().length-2);
this.minutes = Math.floor(rm);
var rs = (rm*mp-this.minutes*mp)/mp*60, sp = Math.pow(10, rs.toString().length-2);
if(displayMilliseconds){
this.seconds = Math.floor(rs);
this.milliseconds = Math.round((rs*sp-this.seconds*sp)/sp*1000);
}
else{
this.seconds = Math.round(rs);
}
this.convert = function(){
return this.hours.toString().replace(/^([0-9])$/, '0$1')+':'+this.minutes.toString().replace(/^([0-9])$/, '0$1')+':'+this.seconds.toString().replace(/^([0-9])$/, '0$1');
}
}
StopWatch = function(displayNode, millisecondInterval){
this.hours = this.minutes = this.seconds = this.milliseconds = 0;
this.millisecondInterval = millisecondInterval || 1000;
this.displayNode = displayNode; this.began = false; this.paused = false;
var t = this, ms, iv, fi;
this.begin = function(doneFunc, context){
var c = context || this;
ms = this.hours*3600000+this.minutes*60000+this.seconds*1000+this.milliseconds;
var mc = new MillisecondConverter(ms), dn = this.displayNode, cv = mc.convert();
if(dn.innerHTML || dn.innerHTML === ''){
dn.innerHTML = cv;
}
else{
dn.value = cv;
}
this.began = true;
fi = function(mi){
var nd = new Date, bt = nd.getTime(), ii = t.millisecondInterval;
ms = mi;
iv = setInterval(function(){
var nd = new Date, ct = nd.getTime(), tl = ct-bt;
var mc = new MillisecondConverter(mi-tl), dn = t.displayNode;
if(tl >= mi){
clearInterval(iv); doneFunc.call(c); cv = '00:00:00';
if(dn.innerHTML || dn.innerHTML === ''){
dn.innerHTML = cv;
}
else{
dn.value = cv;
}
t.began = false;
return;
}
cv = mc.convert(); ms -= ii;
if(dn.innerHTML || dn.innerHTML === ''){
dn.innerHTML = cv;
}
else{
dn.value = cv;
}
}, ii);
}
fi(ms);
}
this.pause = function(){
clearInterval(iv); iv = undefined; this.paused = true;
return this;
}
this.resume = function(){
fi(ms); this.paused = false;
return this;
}
}
var cd = new StopWatch(E('remain')), out = E('out');
cd.seconds = 30;
E('btn').addEventListener('click', function(){
if(!cd.began){
out.innerHTML = '';
cd.begin(function(){
out.innerHTML = 'Countdown Complete';
});
}
else{
cd.paused ? cd.resume() : cd.pause();
}
});
});
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>StopWatch</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div id='remain'>00:00:30</div>
<input id='btn' type='button' value='StopWatch' />
<div id='out'></div>
</div>
</body>
</html>

Timer to be displayed on a webpage

I want to add a count up timer to my webpage, as in, a label that contains 0:00:00 should start displaying 0:00:01 and so on until the stop button is clicked.
Is there a simple javascript/jquery solution to this?
<html>
<head>
<title>Home</title>
<script src="jquery-1.11.1.js">
</script>
<script>
$(document).ready(function(){
$("p").click(function(){
//psst. psst.
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="project" placeholder="project"></td>
<td><p id="timer">0:00:00<p></td>
</tr>
</table>
</form>
</body>
</html>
I tried something in Vanilla JS HERE
var seconds=0, minutes=0, hours=0;
var counter;
var stop,start;
var counting = false;
window.onload = function () {
counter = document.getElementById('counter');
stop = document.getElementById('stop');
stop.onclick = function () {
counting = false;
}
start = document.getElementById('start');
start.onclick = function() {
counting = true;
timer();
}
counting = true;
timer();
}
function timer() {
if (seconds >= 60) {
minutes++;
seconds = 0;
}
if (minutes >= 60) {
hours++;
minutes = 0;
}
counter.innerHTML = hours + ":" + minutes + ":" + seconds;
if (counting) {
seconds++;
setTimeout(timer, 1000);
}
}
If you need more info leave a comment..
time.js
function time(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
// "setTimeout" call function "time" every 1 second (1000 milliseconds)
setTimeout('time("'+id+'");','1000');
return true;
}
HTML
<html>
<head>
<title>Time in Javascript</title>
<script type="text/javascript" src="time.js"></script>
</head>
<body>
<span id="time"></span>
<script type="text/javascript">window.onload = time('time');</script>
</body>
</html>
Try this way
Use https://github.com/jchavannes/jquery-timer
Include this files in head
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript">
<script src="http://jchavannes.com/include/scripts/3p/jquery.timer.js" type="text/javascript">
Script
var Example1 = new (function() {
var $stopwatch, // Stopwatch element on the page
incrementTime = 70, // Timer speed in milliseconds
currentTime = 0, // Current time in hundredths of a second
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
},
init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
$(init);
});
function formatTime(time) {
var min = parseInt(time / 6000),
sec = parseInt(time / 100) - (min * 60),
hundredths = pad(time - (sec * 100) - (min * 6000), 2);
return (min > 0 ? pad(min, 2) : "00") + ":" + pad(sec, 2) + ":" + hundredths;
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {str = '0' + str;}
return str;
}
Example1();
DEMO
By using setInterval and Date
You can use button to stop and start timer.
var d = new Date();
d.setHours(0,0,0,0);
setInterval((function(){
return function(){
d.setSeconds(d.getSeconds()+1);
var t = d.toLocaleTimeString("en-US", {hour12: false});
document.getElementById("demo").innerHTML = t;
}
})(), 1000);
Fiddle Demo
Please try this fiddle for your solution.
JS.
var hour = 0;
var min = 0;
var second = 0;
var i=setInterval(function(){
second++;
if(second > 59){
second = 0;
min++;
if(min>59){
hour++;
min = 0;
}
}
var timer_time = (hour > 9 ? hour : '0'+hour)+':'+(min > 9 ? min : '0'+min)+':'+(second > 9 ? second : '0'+second);
$('#timer').html(timer_time);
}, 1000);
$('#stop_timer').click(function(){
clearInterval(i);
});
HTML
<p id='timer'>00:00:00</p>
<button id='stop_timer'>Stop Timer</button>
Thanks
Use timing events like documented at http://www.w3schools.com/js/js_timing.asp.

plain count up timer in javascript

I am looking for a simple count up timer in javascript. All the scripts I find are 'all singing all dancing'. I just want a jQuery free, minimal fuss count up timer that displays in minutes and seconds. Thanks.
Check this:
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<label id="minutes">00</label>:<label id="seconds">00</label>
Timer for jQuery - smaller, working, tested.
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
$("#seconds").html(pad(++sec%60));
$("#minutes").html(pad(parseInt(sec/60,10)));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="minutes"></span>:<span id="seconds"></span>
Pure JavaScript:
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
document.getElementById("seconds").innerHTML=pad(++sec%60);
document.getElementById("minutes").innerHTML=pad(parseInt(sec/60,10));
}, 1000);
<span id="minutes"></span>:<span id="seconds"></span>
Update:
This answer shows how to pad.
Stopping setInterval MDN is achieved with clearInterval MDN
var timer = setInterval ( function(){...}, 1000 );
...
clearInterval ( timer );
Fiddle
The following code works as a count-up timer. It's pure JavaScript code which shows hour:minute:second. It also has a STOP button:
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
++totalSeconds;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
if(hour < 10)
hour = "0"+hour;
if(minute < 10)
minute = "0"+minute;
if(seconds < 10)
seconds = "0"+seconds;
document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
}
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it's single digit
s = checkTime(s); // add a leading zero if it's single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.
Extending from #Chandu, with some UI added:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue;
border-radius: 4px;
height: 40px;
width: 100px;
color: white;
font-size: 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: 0;
}
#minutes, #seconds {
font-size: 40px;
}
.bigger {
font-size: 40px;
}
.button {
box-shadow: 0 9px #999;
}
.button:hover {background-color: hotpink}
.button:active {
background-color: hotpink;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>
function pad(val) {
valString = val + "";
if(valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function set_timer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
function stop_timer() {
clearInterval(my_int);
}
</script>
Looks as follows:
Fiddled around with the Bakudan's code and other code in stackoverflow to get everything in one.
Update #1 : Added more options. Now Start, pause, resume, reset and restart. Mix the functions to get desired results.
Update #2 : Edited out previously used JQuery codes for pure JS and added as code snippet.
For previous Jquery based fiddle version : https://jsfiddle.net/wizajay/rro5pna3/305/
var Clock = {
totalSeconds: 0,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
reset: function () {
Clock.totalSeconds = null;
clearInterval(this.interval);
document.getElementById("min").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
delete this.interval;
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
},
restart: function () {
this.reset();
Clock.start();
}
};
document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });
document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });
document.getElementById("resumeButton").addEventListener("click", function () { Clock.resume(); });
document.getElementById("resetButton").addEventListener("click", function () { Clock.reset(); });
document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
<span id="min">00</span>:<span id="sec">00</span>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
<input id="resetButton" type="button" value="Reset">
<input id="restartButton" type="button" value="Restart">
#Cybernate, I was looking for the same script today thanks for your input. However I changed it just a bit for jQuery...
function clock(){
$('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
$('#clock > #seconds').html(pad(totalSeconds%60));
$('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
}
$(document).ready(function(){
clock();
});
the css part:
<style>
#clock {
padding: 10px;
position:absolute;
top: 0px;
right: 0px;
color: black;
}
</style>
Note: Always include jQuery before writing jQuery scripts
Step1: setInterval function is called every 1000ms (1s)
Stpe2: In that function. Increment the seconds
Step3: Check the Conditions
<span id="count-up">0:00</span>
<script>
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;
}
</script>
Check out these solutions:
Compute elapsed time
Just wanted to put my 2 cents in. I modified #Ajay Singh's function to handle countdown and count up Here is a snip from the jsfiddle.
var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
runClock(function(){
console.log('done');
clearInterval(t);
},function(timeElapsed, timeRemaining){
console.log( timeElapsed.seconds );
}, countDown);
}, 100);
https://jsfiddle.net/3g5xvaxe/
Here is an React (Native) version:
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class CountUp extends Component {
state = {
seconds: null,
}
get formatedTime() {
const { seconds } = this.state;
return [
pad(parseInt(seconds / 60)),
pad(seconds % 60),
].join(':');
}
componentWillMount() {
this.setState({ seconds: 0 });
}
componentDidMount() {
this.timer = setInterval(
() => this.setState({
seconds: ++this.state.seconds
}),
1000
);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<View>
<Text>{this.formatedTime}</Text>
</View>
);
}
}
function pad(num) {
return num.toString().length > 1 ? num : `0${num}`;
}
Here is one using .padStart():
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<title>timer</title>
</head>
<body>
<span id="minutes">00</span>:<span id="seconds">00</span>
<script>
const minutes = document.querySelector("#minutes")
const seconds = document.querySelector("#seconds")
let count = 0;
const renderTimer = () => {
count += 1;
minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
seconds.innerHTML = (count % 60).toString().padStart(2, "0");
}
const timer = setInterval(renderTimer, 1000)
</script>
</body>
</html>
From MDN:
The padStart() method pads the current string with another string (repeated, if needed) so that the resulting string reaches the given length. The padding is applied from the start (left) of the current string.
This is how I build timerView element which does not confuse by calling function many times.
function startOTPCounter(countDownDate){
var countDownDate = '21/01/2022 16:56:26';//Change this date!!
var x = setInterval(function() {
var now = new Date().getTime();
var distance = moment(countDownDate, 'DD/MM/YYYY hh:mm:ss').toDate().getTime() - now;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timerView").innerHTML = minutes + "min " + seconds + "sn";
if (distance < 0) {
clearInterval(x);
// document.location.reload();
document.getElementById("timerView").innerHTML = "Expired!";
}
}, 1000);
if(window.preInterval != undefined){
clearInterval(window.preInterval);
}
window.preInterval = x;
//if(sessionStorage.preInterval != undefined){
// clearInterval(sessionStorage.preInterval);
//}
//sessionStorage.preInterval = x;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<html>
<head>
</head>
<body>
<div>
<p style="color:red; font-size: 15px; text-align:center; " id='timerView'></p>
<input type="button" name="otpGonder" value="Send Again" class="buton btn btn-default " onclick="startOTPCounter()" id="otpGonder">
</div>
</body>
</html>

Categories

Resources