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.
Related
I am a new learner. I am making a countdown project that gets input from the user and then countdown the time. It rings an alarm after every 5 seconds. But after getting the end-numbers 00:00 it does not stop. It continuously rings the alarm. Please check the code.
<span id="min">00</span>
<span>:</span>
<span id="snd">00</span>
<audio id="myAudio">
<source src="beep-02.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button class="btn" id="start" onclick="timer.start();">START</button>
<span class="mx-3"></span>
<button class="btn" id="set" onclick="location.href='time-selecter.html';">SET</button>
<script type="text/javascript">
var hh = localStorage.getItem("a")
var mm = localStorage.getItem("b")
var ss = localStorage.getItem("c")
function yourfunction() {
document.getElementById("hr").innerHTML = hh;
document.getElementById("min").innerHTML = mm;
document.getElementById("snd").innerHTML = ss;
}
window.onload = yourfunction;
//timer
var start_time = 0;
var elapsed_time = 0;
var requested_time;
var timer_inter;
var timer = {
start: function() {
start_time = new Date();
requested_time = toMs(document.getElementById('hr').innerHTML, document.getElementById('min').innerHTML, document.getElementById('snd').innerHTML, 0);
timer_inter = setInterval(function() {
elapsed_time = new Date() - start_time;
document.getElementById('time').innerHTML = toTimeFormat(requested_time - elapsed_time + 1000, 'hh:mm:ss');
//+ 1000ms because the seconds are rounded down, so without it when the timer SHOWS 00:00:00, it will have to wait 1s before stopping
if (elapsed_time >= requested_time) {
timer.stop();
timer.end();
}
}, 0);
},
stop: function() {
clearInterval(timer_inter);
},
end: function() {
document.getElementById('time').innerHTML = '00:00';
}
};
var x = document.getElementById("myAudio");
function yourFunction(){
setTimeout(yourFunction, 5000);
x.play();
}
function pausefn(){
x.pause();
x.currentTime = 0;
}
$("#start").click(function(){
yourFunction();
});
/*------------------------------*/
/*UTILITY*/
/*------------------------------*/
function toTimeFormat(t, format) {
function addDigit(n) {
return (n < 10 ? '0':'') + n;
}
var ms = t % 1000;
t = (t - ms) / 1000;
var secs = t % 60;
t = (t - secs) / 60;
var mins = t % 60;
var hrs = (t - mins) / 60;
ms = (ms < 10) ? '00' : (ms < 100) ? '0' + Math.floor(ms / 10) : Math.floor(ms / 10);
if (format === 'hh:mm:ss') {
return addDigit(mins) + ':' + addDigit(secs);
} else if (format === 'mm:ss:msms') {
return addDigit(mins) + ':' + addDigit(secs) + ':' + ms;
}
}
function toMs(h, m, s, ms) {
return (ms + s * 1000 + m * 1000 * 60 + h * 1000 * 60 * 60);
}
</script>
I am making a countdown project. I tried to stop an alarm when countdown at 00:00 time. But it countinousily rings the alarm untill I close the browser.
I have a simple code but there is a problem
How do I make this code work in a minute and a second system
Tried but only work a second!
You can look at the code
https://jsfiddle.net/o183pdqg/1/
I hope for help because I am really tired and I am looking for a solution
function secondPassed() {
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
adsElement.style.display = '';
countdownElement.innerHTML = remainingSeconds;
var interval = setInterval(function() {
countdownElement.innerHTML = --remainingSeconds;
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
you need to put variable minutes and seconds within setInterval function to make it work. Convert the time var remainingSeconds = seconds * 1000; from second to milisecond so it will make it easier when working with new Date().getTime().
To get minutes and second, try it using modulus (%) operator to get remaining time from your starting time.
var availability = true
function secondPassed() {
if (!availability) {
return false
}
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
availability = false
adsElement.style.display = '';
contentElement.style.display = 'none';
function runInterval () {
var remainingSeconds = seconds * 1000;
let minutes = Math.floor(remainingSeconds % (1000*60*60)/ (1000*60));
let seconds1 = Math.floor(remainingSeconds % (1000*60) / 1000);
if (seconds1 < 10) {
seconds1 = "0" + seconds1;
}
document.getElementById('countdown').innerHTML = minutes + ":" + seconds1;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
availability = true
}
}
var interval = setInterval(function() {
// countdownElement.innerHTML = --remainingSeconds;
runInterval ()
}, 1000);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
</body>
</html>
You can try with this answer
secondPassed = () => {
let remainingSeconds = 120;
const countdownElement = document.getElementById('countdown');
const contentElement = document.getElementById('content');
const adsElement = document.getElementById('ads');
adsElement.style.display = '';
const getPad = (num) => {
return (num < 10) ? '0' + num.toString() : num.toString();
}
const interval = setInterval(() => {
let minutes = Math.floor(remainingSeconds / 60) % 60;
let seconds = getPad(remainingSeconds % 60);
countdownElement.innerHTML = `${minutes} : ${seconds}`;
remainingSeconds--;
if (remainingSeconds == 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}
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>
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();
}
}
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>