I am trying to make a simple plugin to calculate date and time by this code:
<div id="timer"></div>
<script>
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#timer").append( "<p>"+days+"</p>" );
$("#timer").append( "<p>"+hours+"</p>" );
$("#timer").append( "<p>"+minutes+"</p>" );
$("#timer").append( "<p>"+seconds+"</p>" );
var timer = setTimeout('timeCounter',1000);
};
$("#timer").timeCounter("june 16, 2014 00:01:00");
</script>
the code is working fine but I am having problem on displaying actual count down on numbers! can you please let me know how to fix this?
Thanks
Following displays count down in seconds:
$.fn.timeCounter = function(time) {
var target = new Date(time);
var now = new Date();
var timeDiff = target.getTime() - now.getTime();
// count down logic
setTimeout(function cdtd(){
if (timeDiff > 0){
// reduce one seconds
timeDiff-=1000;
// change this to a more dedicated display per your requirements
$('#timer').html(timeDiff/1000);
// next one second, reference to cdtd
setTimeout(cdtd,1000);}
},1000);
}
See working sample:
http://jsfiddle.net/danyu/X33kv/
Related
I need help with a countdown. I used the following script to generate a countdown.
var endTime = new Date(2016, 04, 10).getTime() / 1000;
function setClock() {
var elapsed = new Date().getTime() / 1000;
var totalSec = endTime - elapsed;
var d = parseInt( totalSec / 86400 );
var h = parseInt( totalSec / 3600 ) % 24;
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = d;
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
I just want to see the hours - in this moment, when I delete the days, minutes, seconds, it will just show 24 hours even if it's a longer time.
If i undertand your question, this should work :
function setClock() {
var elapsed = new Date().getTime() / 1000;
var totalSec = endTime - elapsed;
document.getElementById('timeRemaining').innerHTML = parseInt( totalSec / 3600 );
setTimeout(setClock, 1000);
}
If you only want to count down the hours until your date (may 10, 2016), here's one solution for you:
var endTime = new Date('2016/05/10').getTime()/1000;
function setClock(){
var currDate = new Date().getTime()/1000;
var timeRemaining = Math.ceil((endTime - currDate)/(60*60));
/*time remaining is in hours. Math.ceil will make sure that 1 hour is shown
if time remaining is less than 1 hour unless you want to show mins */
document.getElementById('timeRemaining').innerHTML = timeRemaining;
setTimeout(setClock, 1000);
}
setClock();
https://jsbin.com/buxetenika/edit?html,js,output
This should get you started...hope this helps
I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged in to the current time.
Here is my code:-
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var markMinutes = markDate.getMinutes();
var markSeconds = markDate.getSeconds();
var currDate = new Date();
var currMinutes = currDate.getMinutes();
var currSeconds = currDate.getSeconds();
var minutes = currMinutes - markMinutes;
if(minutes < 0) { minutes += 60; }
var seconds = currSeconds - markSeconds;
if(seconds < 0) { seconds += 60; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
var hours = 0;
if(minutes == 59 && seconds == 59) { hours++; }
if(hours < 10) { hours = "0" + hours; }
var timeElapsed = hours+':'+minutes+':'+seconds;
document.getElementById("timer").innerHTML = timeElapsed;
setTimeout(function() {updateClock()}, 1000);
}
The output is correct upto 00:59:59 but after that that O/P is:
00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00
How can I solve this and is there a more efficient way I can do this?
Thank you.
No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.
There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered here.
var start = Date.now();
setInterval(function() {
document.getElementById('difference').innerHTML = Date.now() - start;
// the difference will be in ms
}, 1000);
<div id="difference"></div>
There's too much going on here.
An easier way would just be to compare markDate to the current date each time and reformat.
See Demo: http://jsfiddle.net/7e4psrzu/
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var currDate = new Date();
var diff = currDate - markDate;
document.getElementById("timer").innerHTML = format(diff/1000);
setTimeout(function() {updateClock()}, 1000);
}
function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
return ((numhours<10) ? "0" + numhours : numhours)
+ ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
+ ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}
markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:
const showElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = 1000 * 60
const HOUR = 1000 * 60 * 60
const DAY = 1000 * 60 * 60 * 24
const MONTH = 1000 * 60 * 60 * 24 * 30
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
// const elapsed = ((new Date()).valueOf() - timestamp)
const elapsed = 1541309742360 - timestamp
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
const createdAt = 1541301301000
console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.
If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).
Here are the scaling units in more DRY form:
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
We can also use console.time() and console.timeEnd() method for the same thing.
Syntax:
console.time(label);
console.timeEnd(label);
Label:
The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.
let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));
// Start Timer
console.time('x');
promise.then((result) => {
console.log(result);
// End Timer
console.timeEnd('x');
});
You can simply use performance.now()
Example:
start = performance.now();
elapsedTime = performance.now() - start;
var hours = 0;
if(minutes == 59 && seconds == 59)
{
hours = hours + 1;
minutes = '00';
seconds == '00';
}
I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.
I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be added.
(function(w){
var timeStart,
timeEnd,
started = false,
startTimer = function (){
this.timeStart = new Date();
this.started = true;
},
getPartial = function (end) {
if (!this.started)
return 0;
else {
if (end) this.started = false;
this.timeEnd = new Date();
return (this.timeEnd - this.timeStart) / 1000;
}
},
stopTime = function () {
if (!this.started)
return 0;
else {
return this.getPartial(true);
}
},
restartTimer = function(){
this.timeStart = new Date();
};
w.Timer = {
start : startTimer,
getPartial : getPartial,
stopTime : stopTime,
restart : restartTimer
};
})(this);
Start
Partial
Stop
Restart
What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):
var trace = console.log
function elapsed(op) {
this.op = op
this.t0 = Date.now()
}
elapsed.prototype.show = function() {
trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}
to be used - for instance:
function debug_counters() {
const e = new elapsed('debug_counters')
const to_show = visibleProducts().length
e.show('to_show', to_show)
}
A count up timer that won't reset on refresh
var test;
var pageVisisted = new Date();
test = setInterval(function () {
var timeOnSite = new Date() - pageVisisted;
var secondsTotal = timeOnSite / 1000;
var minutes = Math.floor(secondsTotal / 60) % 3600;
var seconds = Math.floor(secondsTotal) % 60;
document.getElementById('counter').innerHTML = minutes + "." + seconds;
}, 1000);
I am spending lot of hours to setup the timer.But cannot able to done it.Anybody know how to solve these kind of Errors.
For Example:
If I refresh these page at 1.26 seconds,countdown again started as 0.But it have to started at 1.26 after refresh.Can you solve that and tell me how to fix it.
You can store pageVisited value in localStorage (or better I guess in sessionStorage):
var pageVisited = +localStorage.pageVisited || +new Date();
var test = setInterval(function() {
var timeOnSite = new Date() - pageVisited;
var secondsTotal = timeOnSite / 1000;
var minutes = Math.floor(secondsTotal / 60) % 3600;
var seconds = Math.floor(secondsTotal) % 60;
document.getElementById('counter').innerHTML = minutes + "." + seconds;
}, 1000);
if (!localStorage.pageVisited) {
localStorage.pageVisited = pageVisited;
}
Demo: http://jsfiddle.net/HjxLX/
If you want the timer to be cleared after you close the browser window use sessionStorage.
IE support: IE8+.
I have the following code for a countdown timer. I need to convert the JavaScript portion to jQuery. The countdown timer starts on page load. How can I do that, as I have to load the diffTime function on load of the page. Please help me. Thanks in advance.
Edit: I got that the jquery call can not access ** function Tick() ** from ** function CreateTimer() ** . Is there any library for ** setTimeout() ** in jQuery? As I know so far, it is native to JS.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
//UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
//alert("Time's up!")
document.getElementById("timeMsg").innerHTML = "Market closed!! ";
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : + Time;
}
function diffTime(){
var startTime = 10*60 + 30; //starting time in minute
var lastTime = 16*60 + 30; //ending time in minutes
var thisTime = new Date(); // now
var currentYear = thisTime.getFullYear();
var currentMonth = thisTime.getMonth();
var currentDay = thisTime.getUTCDate();
var currentHour = thisTime.getHours();
var currentMinute = thisTime.getMinutes();
var currentTime = currentHour*60 + currentMinute; //current time in minute
if(currentTime >= startTime && currentTime < lastTime){
var endTime = new Date(currentYear,currentMonth,currentDay,16,30); // 4:30pm
var diff = endTime.getTime() - thisTime.getTime(); // now
var remainTime = diff / (1000); // positive number of days
remainTime = Math.ceil(remainTime);
CreateTimer("timer", remainTime);
}else{
document.getElementById("timeMsg").innerHTML = "Market closed!! ";
document.getElementById("timer").innerHTML = "00:00:00";
}
}
window.onload = diffTime;
</script>
</head>
<body>
<div><span id="timeMsg">Elapsed time remain: </span><b><span id='timer'></span></b></div>
</body>
Call the function in document.ready()
$( document ).ready( function ()
{
diffTime();
});
If you want it to start after the entire (ie. images, objects, etc.) page has loaded:
$(window).load(function() {}
Otherwise you can start the timer when the HTML has been loaded & DOM is ready:
$(document).ready(function() {}
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