I made a timer countdown in js. It runs after a click event. The issue is when i click again the timer doesn't reset and it creates another countdown but the former one still count. I would like to reset the first when i click again.
i tried to use a clear interval but i'm not sure to use it right.
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback()
}
})()
}
var submitBtn = document.getElementById('yes');
submitBtn.addEventListener("click", function(e) {
// countdown element
var countdownel = document.getElementById('clockdiv');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('end');
})
})
<button id="yes"></button>
<div><span id="clockdiv">countdown
</span></div>
You need to clear the last timeout on each click.
To do that create a global variable and assign the timeout into. After you can use clearTimeout on each click
See live demo
var timeout;
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
if (dist > 0) {
timeout = setTimeout(timer, 1000);
} else {
callback()
}
})()
}
var submitBtn = document.getElementById('yes');
submitBtn.addEventListener("click", function(e) {
clearTimeout(timeout)
// countdown element
var countdownel = document.getElementById('clockdiv');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('end');
})
})
<button id="yes">yes</button>
<div><span id="clockdiv">countdown
</span></div>
Note : You are simulate setInterval with setTimeout. I think it's better to use directly setInterval in your case
setTimeout(timer, 1000) returns internal timer ID. To stop the function you've passed in setTimeout() you have to stop the timer by calling clearTimeout(ID) function and pass internal timer ID you've got from setTimeout()
Also I recommend you to use setInterval():
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
to stop myTimer function clear myVar
clearTimeout(myVar);
Related
I have a timer which I am testing, it seems there is a bit of drift between when the minute countdown goes down by 1 and seconds whenever it reaches 59 seconds ()ie every minute:-
How can I alter this so they are both in sync?
my code is the following:-
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - ((now() - initTick) / 1000);
timeRemaining = timeRemaining >= 0 ? timeRemaining : 0;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining.toFixed() % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
if (timeRemaining > 0) {
setTimeout(tick, delay);
}
}
var countdown = 600; // time in seconds until user may login again
var delay = 20; // time (in ms) per tick
var initTick = now(); // timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer"); // element to have countdown written to
setTimeout(tick, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle: https://jsfiddle.net/robbiemcmullen/cer8qemt/1/
The issue is the precision is not the same for minutes and seconds.
You need to round to the nearest second before /60 / %60.
Consider: exactly 9 mins remaining:
var x = 540;
console.log(x.toFixed() % 60, Math.floor(x / 60));`
Output is: (0,9)
Then consider the call 20 ms later:
var x = 539.980;
console.log(x.toFixed() % 60, Math.floor(x / 60));
the output is now: (0, 8).
So the seconds haven't changed (yet) but the minute does.
Here is a version using setInterval and removing the use of .toFixed ()
Why do you use an interval of 20ms and not 1 second?
//method for countdown timer
$(document).ready(function() {
function now() {
return window.performance ? window.performance.now() : Date.now();
}
function tick() {
var timeRemaining = countdown - elapsedTime;
var countdownMinutes = Math.floor(timeRemaining / 60);
var countdownSeconds = timeRemaining % 60;
countdownTimer.innerHTML = countdownMinutes + ":" + countdownSeconds;
if (countdownSeconds < 10) {
countdownTimer.innerHTML = countdownMinutes + ":" + 0 + countdownSeconds;
}
++elapsedTime;
return timeRemaining;
}
var countdown = 600;
var elapsedTime = 0;
var timeRemaining;
// countdown: time in seconds until user may login again
//var delay = 20;
// delay: time (in ms) per tick
var initTick = now(); // initTick: timestamp (in ms) when script is initialized
var countdownTimer = document.querySelector(".timer");
// countdownTimer: element to have countdown written to
var interval = setInterval(function() {
if(tick() <= 0) {
clearInterval(interval);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
js fiddle https://jsfiddle.net/ud3wm8t1/
I have a stopwatch timer built in JS that counts up from 0 using hours, minutes, seconds and milliseconds. Currently when the user hits the stop button the value from the timer is appended to a hidden input element for form submission. I need to convert whatever the time is to just hourly to where it is appended to that hidden input. So right now if my clock is stopped at 25 minutes and 00 seconds, the value in the input is 00:25:00, I would like it to convert the time to something like .25 (for hours)
For example, for 30 minutes the value appended to my hidden input would be .5, for 45 minutes it would be .75, so on and so fourth.
Here is the stopwatch script, the Stop function is where the value is appended to our hidden input, just need to make sure it is converted to hourly
<script type="text/javascript">
var clsStopwatch = function () {
var startAt = 0;
var lapTime = 0;
var now = function () {
return (new Date()).getTime();
};
this.start = function () {
startAt = startAt ? startAt : now();
};
this.stop = function () {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
this.time = function () {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor(time / (3600 * 1000));
time = time % (3600 * 1000);
m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2);
//newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}
</script>
If I correctly understand what you need, this is your solution:
function millisecondsToHours(amountMS) {
return amountMS / 3600000;
}
I have a timer that I want to start by calling
countdownTimer.start(600,'/page2.html');
After showing the timer counting down from 600 seconds, it will redirect to page2.html
I also want to resume a previous timer (from a cookie) by calling the following. I'm just using cookies to save the value where it left off, so if the page is refreshed it will resume counting instead of starting over.
countdownTimer.resume(123, '/page2.html');
I'm getting all kinds of errors, about inner html not being defined (I assume this is related to the variables at the top of the function not being called).
can someone please help me understand how to create javascript objects like this? it has always confused me :/
var countdownTimer = (function() {
var elem = document.getElementById("countdown");
var url = '';
var end = 60;
var _second = 1000;
var _minute = 60000;
var _hour = 3600000;
var timer;
function pad (n, amount) {
return n > parseInt(Array(amount).join("9")) ? "" + n : "0" + n;
}
function showRemaining () {
var now = new Date().getTime();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
elem.innerHTML = "Offer Expired";
window.location.href = url;
return;
}
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var milliseconds = Math.floor( (distance % _second) );
elem.innerHTML = pad(minutes, 2) + ' <span>:</span> ';
elem.innerHTML += pad(seconds, 2) + ' <span>:</span> ';
elem.innerHTML += pad(milliseconds, 3);
}
var start = function (secondsToExpire, url) {
url = url;
end = new Date().getTime() + (secondsToExpire * 1000);
timer = setInterval(showRemaining, 1);
}
var resume = function (customEnd, url) {
url = url;
end = customEnd;
timer = setInterval(showRemaining, 1);
}
var currentTime = function () {
return 500;
}
return {
start: start,
resume: resume,
currentTime: currentTime
};
})();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to run the Clock (date and time) 4 times speeder
I'm trying to make a clock that starts at a time value (hh:mm:ss) that I've supplied, and runs at 4x speed (for the server time of an online game that runs 4x actual time). I've modified a free clock that I found online to do this, but it only works for every other minute (try the code below to see exactly what I mean if that doesn't make sense).
var customClock = (function () {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10 ? '0' : '') + n;
}
function formatTime(d) {
t1 = d.getHours();
t2 = d.getMinutes();
t3 = d.getSeconds() * 4;
if (t3 > 59) {
t3 = t3 - 60;
t2 = t2 + 1;
}
if (t2 > 59) {
t2 = t2 - 60;
t1 = t1 + 1;
}
if (t1 > 23) {
t1 = 0;
}
return addZ(t1) + ':' + addZ(t2) + ':' + addZ(t3);
}
return function (s) {
var now = new Date();
var then;
var lag = 1015 - now.getMilliseconds();
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function () {
customClock('00:00:00');
};
Any idea why this is happening? I'm pretty new to Javascript and this is definitely a little hack-ey. Thanks
i take the orginal time and substract it from the current then multiply it by 4 and add it to the orginal time. I think that should take care or the sync problem.
(function(){
var startTime = new Date(1987,08,13).valueOf() //save the date 13. august 1987
, interval = setInterval(function() {
var diff = Date.now() - startTime
//multiply the diff by 4 and add to original time
var time = new Date(startTime + (diff*4))
console.log(time.toLocaleTimeString())
}, 1000)
}())
How to use with a custom date (use the Date object)
Date(year, month, day, hours, minutes, seconds, milliseconds)
var lag = 1015 - now.getMilliseconds(); is attempting to "run this again a smidge (15 ms) after the next clock tick". Make this value smaller (divide by 4?), and this code will run more frequently.
Next up, get it to show 4x the current clock duration. Similar problem: multiply now's details by 4 either inside or outside formatTime()
I would first create a Clock constructor as follows:
function Clock(id) {
var clock = this;
var timeout;
var time;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.stop = stop;
this.start = start;
var element = document.getElementById(id);
function stop() {
clearTimeout(timeout);
}
function start() {
timeout = setTimeout(tick, 0);
time = Date.now();
}
function tick() {
time += 1000;
timeout = setTimeout(tick, time - Date.now());
display();
update();
}
function display() {
var hours = clock.hours;
var minutes = clock.minutes;
var seconds = clock.seconds;
hours = hours < 10 ? "0" + hours : "" + hours;
minutes = minutes < 10 ? "0" + minutes : "" + minutes;
seconds = seconds < 10 ? "0" + seconds : "" + seconds;
element.innerHTML = hours + ":" + minutes + ":" + seconds;
}
function update() {
var seconds = clock.seconds += 4;
if (seconds === 60) {
clock.seconds = 0;
var minutes = ++clock.minutes;
if (minutes === 60) {
clock.minutes = 0;
var hours = ++clock.hours;
if (hours === 24) clock.hours = 0;
}
}
}
}
Then you can create a clock and start it like this:
var clock = new Clock("clock");
clock.start();
Here's a demo: http://jsfiddle.net/Nt5XN/
This question already has answers here:
How to measure time taken by a function to execute
(30 answers)
Closed 9 years ago.
I am looking for some JavaScript simple samples to compute elapsed time. My scenario is, for a specific point of execution in JavaScript code, I want to record a start time. And at another specific point of execution in JavaScript code, I want to record an end time.
Then, I want to calculate the elapsed time in the form of: how many Days, Hours, Minutes and Seconds are elapsed between end time and start time, for example: 0 Days, 2 Hours, 3 Minutes and 10 Seconds are elapsed.
Any reference simple samples? :-)
Thanks in advance,
George
Try something like this (FIDDLE)
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;
Try this...
function Test()
{
var s1 = new StopWatch();
s1.Start();
// Do something.
s1.Stop();
alert( s1.ElapsedMilliseconds );
}
// Create a stopwatch "class."
StopWatch = function()
{
this.StartMilliseconds = 0;
this.ElapsedMilliseconds = 0;
}
StopWatch.prototype.Start = function()
{
this.StartMilliseconds = new Date().getTime();
}
StopWatch.prototype.Stop = function()
{
this.ElapsedMilliseconds = new Date().getTime() - this.StartMilliseconds;
}
Hope this will help:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>compute elapsed time in JavaScript</title>
<script type="text/javascript">
function display_c (start) {
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh = 1000; // Refresh rate in milli seconds
if( window.start >= end ) {
mytime = setTimeout( 'display_ct()',refresh )
} else {
alert("Time Over ");
}
}
function display_ct () {
// Calculate the number of days left
var days = Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))
var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";
document.getElementById('ct').innerHTML = x;
window.start = window.start - 1;
tt = display_c(window.start);
}
function stop() {
clearTimeout(mytime);
}
</script>
</head>
<body>
<input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
<span id='ct' style="background-color: #FFFF00"></span>
</body>
</html>
Something like a "Stopwatch" object comes to my mind:
Usage:
var st = new Stopwatch();
st.start(); //Start the stopwatch
// As a test, I use the setTimeout function to delay st.stop();
setTimeout(function (){
st.stop(); // Stop it 5 seconds later...
alert(st.getSeconds());
}, 5000);
Implementation:
function Stopwatch(){
var startTime, endTime, instance = this;
this.start = function (){
startTime = new Date();
};
this.stop = function (){
endTime = new Date();
}
this.clear = function (){
startTime = null;
endTime = null;
}
this.getSeconds = function(){
if (!endTime){
return 0;
}
return Math.round((endTime.getTime() - startTime.getTime()) / 1000);
}
this.getMinutes = function(){
return instance.getSeconds() / 60;
}
this.getHours = function(){
return instance.getSeconds() / 60 / 60;
}
this.getDays = function(){
return instance.getHours() / 24;
}
}
var StopWatch = function (performance) {
this.startTime = 0;
this.stopTime = 0;
this.running = false;
this.performance = performance === false ? false : !!window.performance;
};
StopWatch.prototype.currentTime = function () {
return this.performance ? window.performance.now() : new Date().getTime();
};
StopWatch.prototype.start = function () {
this.startTime = this.currentTime();
this.running = true;
};
StopWatch.prototype.stop = function () {
this.stopTime = this.currentTime();
this.running = false;
};
StopWatch.prototype.getElapsedMilliseconds = function () {
if (this.running) {
this.stopTime = this.currentTime();
}
return this.stopTime - this.startTime;
};
StopWatch.prototype.getElapsedSeconds = function () {
return this.getElapsedMilliseconds() / 1000;
};
StopWatch.prototype.printElapsed = function (name) {
var currentName = name || 'Elapsed:';
console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
Benchmark
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
Output
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]
performance.now() is optional - just pass false into StopWatch constructor function.
This is what I am using:
Milliseconds to a pretty format time string:
function ms2Time(ms) {
var secs = ms / 1000;
ms = Math.floor(ms % 1000);
var minutes = secs / 60;
secs = Math.floor(secs % 60);
var hours = minutes / 60;
minutes = Math.floor(minutes % 60);
hours = Math.floor(hours % 24);
return hours + ":" + minutes + ":" + secs + "." + ms;
}
First, you can always grab the current time by
var currentTime = new Date();
Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js
If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.
Good luck.
<script type="text/javascript">
<!-- Gracefully hide from old browsers
// Javascript to compute elapsed time between "Start" and "Finish" button clicks
function timestamp_class(this_current_time, this_start_time, this_end_time, this_time_difference) {
this.this_current_time = this_current_time;
this.this_start_time = this_start_time;
this.this_end_time = this_end_time;
this.this_time_difference = this_time_difference;
this.GetCurrentTime = GetCurrentTime;
this.StartTiming = StartTiming;
this.EndTiming = EndTiming;
}
//Get current time from date timestamp
function GetCurrentTime() {
var my_current_timestamp;
my_current_timestamp = new Date(); //stamp current date & time
return my_current_timestamp.getTime();
}
//Stamp current time as start time and reset display textbox
function StartTiming() {
this.this_start_time = GetCurrentTime(); //stamp current time
document.TimeDisplayForm.TimeDisplayBox.value = 0; //init textbox display to zero
}
//Stamp current time as stop time, compute elapsed time difference and display in textbox
function EndTiming() {
this.this_end_time = GetCurrentTime(); //stamp current time
this.this_time_difference = (this.this_end_time - this.this_start_time) / 1000; //compute elapsed time
document.TimeDisplayForm.TimeDisplayBox.value = this.this_time_difference; //set elapsed time in display box
}
var time_object = new timestamp_class(0, 0, 0, 0); //create new time object and initialize it
//-->
</script>
<form>
<input type="button" value="Start" onClick="time_object.StartTiming()"; name="StartButton">
</form>
<form>
<input type="button" value="Finish" onClick="time_object.EndTiming()"; name="EndButton">
</form>
<form name="TimeDisplayForm">
Elapsed time:
<input type="text" name="TimeDisplayBox" size="6">
seconds
</form>
write java program that enter elapsed time in seconds for any cycling event & the output format should be like (hour : minute : seconds ) for EX : elapsed time in 4150 seconds= 1:09:10