I need to show a countdown timer. I get time from my server and should count down to zero, based on the following:
var now = new Date().getTime();
var timeRemaining = endTime - now;
.... I start the contdown timer with timeRemining
What happens is when I start the timer in two different tabs, the timer is off by about 2 seconds.
If I do this in one tab and another private window/tab, the timer can be different much much more.
Is there something I can do about this?
var end = new Date('2015-10-27T13:00:00');
var endTime = end.getTime();
var div = document.getElementById('time');
setInterval(function() {
var now = new Date().getTime();
var timeRemaining = endTime - now;
var seconds = timeRemaining / 1000;
div.innerText = Math.floor(seconds);
}, 1000);
<div id="time"></div>
Related
I am trying to create a countdown timer from the difference between datetimes.
How can I set the frequency and interval using both minutes and seconds?
What I originally had was working in just minutes but when I refresh the page it starts from the nearest minute and does not include seconds.
I know below var frequency = mins*60 is incorrect as I need to factor in seconds but how can I do this with the format mm:ss?
now = 2022-07-01 15:01:00
input_time = 2022-07-01 15:00:00
exam_end_time = 2022-07-01 15:05:00
00:04
HTML
<div id="demo"></div>
JS
<script>
var diff = document.getElementById('demo');
var now = moment.utc().format("YYYY-MM-DD HH:mm:ss");
var input_time = '2022-07-01 15:00:00';
var exam_end_time ='2022-07-01 15:05:00';
var mins = moment.utc(moment(exam_end_time, "YYYY-MM-DD HH:mm:ss"),diff(moment(now, "YYYY-MM-DD HH:mm:ss"))).format("mm:ss")
// Returns 00:04
var frequency = mins*60
var refreshIntervalId = setIntervan(() => {
const formatted = moment.utc(frequency--*1000.format("mm:ss");
diff.innerHTML = formatted;
}, 1000;
// When countdown hits zero. Stop the clock and show "Expired"
setTimeout(() => {
if(mins <= 00:00) {
diff.innerHTML = "Expired";
clearInterval(refreshIntervalId);
}},frequency*1000;
</script>
After some research, I understand the most accurate way to create a timer in Javascript is to compare the elapsed time from a starting point using date.now() -as this answer suggests.
var startTime = Date.now();
var interval = setInterval(function() {
var elapsedTime = Date.now() - startTime;
var time = (elapsedTime / 1000).toFixed(3);
console.log(time);
}, 10);
This provides the accuracy I am looking for, but I am looking to make this timer reset itself after a certain value (let's say var total = 12000). This value is determined by the length of a video playlist (I am building a 'live' playhead for a video program) and is a variable.
I'm stuck how to go about this, as the counter is counting elapsed time from a certain point in time, it doesn't quite fit the logic of what I am looking for. Any suggestions would be appreciated.
You could use a .setTimeout() at the end of your code to restart your .setInterval(), after the desired time has passed
function runInterval (loopAfter) {
var startTime = Date.now();
var interval = setInterval(function() {
var elapsedTime = Date.now() - startTime;
var time = (elapsedTime / 1000).toFixed(3);
console.log(time);
}, 10);
setTimeout(() => {
clearInterval(interval);
runInterval(loopAfter);
}, loopAfter);
}
runInterval(5000);
Try this:
var startTime = Date.now();
let total = 0;
var interval = setInterval(function() {
if (total === 12000) {
total = 0;
startTime = Date.now();
} else {
total++;
var elapsedTime = Date.now() - startTime;
var time = (elapsedTime / 1000).toFixed(3);
}
console.log(time);
}, 10);
Like on 7 am in the morning the code runs and moves a div to another div
here is my code
jQuery(document).ready(function(){
var tomorrow_sec = jQuery("#day").html();
jQuery("#day-dest").html(tomorrow_sec);
jQuery("#day").html(" ");
});
The code will run when you load the page.
If you want to move something, then you need to check every time you load the page what the time is, and then try to open in x milliseconds OR you need to run an interval and see if the time has been reached.
Method one:
$(function(){
var now = new Date(); // or new Date(time in milliseconds from server)
var sevenAm = new Date(now.getFullYear(), now.getMonth(), now.getDate(),7,0,0,0)
var diff = sevenAm.getTime() - now.getTime();
if (diff < 0) sevenAm.setDate(sevenAm.getDate()+1); // tomorrow
diff = sevenAm.getTime() - now.getTime();
var tId = setTimeout(function() {
var tomorrow_sec = $("#day").html();
$("#day-dest").html(tomorrow_sec);
$("#day").empty();
},diff);
});
Method 2
$(function() {
var tId = setInterval(function() {
var now = new Date();
var sevenAm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 7, 0, 0, 0)
var diff = sevenAm.getTime() - now.getTime();
if (diff < 0) sevenAm.setDate(sevenAm.getDate() + 1); // tomorrow
diff = sevenAm.getTime() - now.getTime();
if (diff <= 60000) { // within a minute - you could use Math.abs here
var tomorrow_sec = $("#day").html();
$("#day-dest").html(tomorrow_sec);
$("#day").empty();
}
}, 1000); // 30000: test every 30 seconds
});
Set an interval on page load, which will run on every 1 second. and will check the time. If the time is 07:00 am to 09:59 am then it will remove content from a div and paste into another div.
You can check the working fiddle here - Example
To test it, uncomment the line var today = new Date('01/01/2011 07:00:00'); and comment the next line var today = new Date();
var interval = setInterval(myfunction, 1000);
function myfunction() {
//var today = new Date('01/01/2011 07:00:00');
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes();
//console.log(time);
if (time >= '7:0' && time <= '9:30') {
clearInterval(interval);
var tomorrow_sec = jQuery("#day").html();
jQuery("#day-dest").html(tomorrow_sec);
jQuery("#day").html("");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="day">
content of day div
</div>
<div id="day-dest">
fghgjgh
</div>
Im making a countdown timer and I want the time to refresh every second. Im using setInterval but it only seems to be running once instead of every second. What is wrong with my code?
var countDown = setInterval(function(){
$('#days').val(daysLeft);
$('#hours').val(hoursLeft);
$('#minutes').val(minLeft);
$('#seconds').val(secLeft);
},1000);
demo: http://jsfiddle.net/EnigmaMaster/pyRR8/14/
You need to recalculate the time left within the interval, otherwise you'll continue to set it to the same value.
Your code was not updating the currentDate variable. I updated the code on jsFiddle and paste it here:
var endDay = new Date('May 24, 2012 11:30:00');
var countDown = setInterval(function(){
var currentDate = new Date();
var daysdecimal = (endDay - currentDate)/(1000*60*60*24);
var daysLeft = Math.floor(daysdecimal);
var hoursdecimal = (daysdecimal - Math.floor(daysdecimal))*24;
var hoursLeft = Math.floor(hoursdecimal);
var minLeft = 60 - currentDate.getMinutes();
var secLeft = 60 - currentDate.getSeconds();
$('#days').val(daysLeft);
$('#hours').val(hoursLeft);
$('#minutes').val(minLeft);
$('#seconds').val(secLeft);
},1000);
want to look like this? I have updated your Jsfiddle
See here : http://jsfiddle.net/pyRR8/23/
So lets say we have 4 Divs (3 hidden, 1 visible), the user is able to toggle between them through javascript/jQuery.
I want to calculate time spent on each Div, and send an xhr containing that time to server to store it in the database. This xhr will be sent when the user toggle the div view.
How can I do that? Any hints will be greatly appreciated.
Thanks,
At any point, you can record a a start/lap time in a variable with:
var start = new Date();
When you want to calculate the elapsed time, simply subtract the stored date from a new Date instance:
var elapsed = new Date() - start;
This will give you the elapsed time in milliseconds. Do additional math (division) to calculate seconds, minutes, etc.
Here you go:
HTML:
<div id="divs">
<div>First</div>
<div class="selected">Second</div>
<div>Third</div>
<div>Fourth</div>
</div>
<p id="output"></p>
JavaScript:
var divs = $('#divs > div'),
output = $('#output'),
tarr = [0, 0, 0, 0],
delay = 100;
divs.click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
setInterval(function() {
var idx = divs.filter('.selected').index();
tarr[idx] = tarr[idx] + delay;
output.text('Times (in ms): ' + tarr);
}, delay);
Live demo: http://jsfiddle.net/7svZr/2/
I keep the times in milliseconds because integers are cleaner and safer (0.1 + 0.2 != 0.3). Note that you can adjust the "precision" (the delay of the interval function) by setting the delay variable.
Here is a reusable class, example is included in code:
/*
Help track time lapse - tells you the time difference between each "check()" and since the "start()"
*/
var TimeCapture = function () {
var start = new Date().getTime();
var last = start;
var now = start;
this.start = function () {
start = new Date().getTime();
};
this.check = function (message) {
now = (new Date().getTime());
console.log(message, 'START:', now - start, 'LAST:', now - last);
last = now;
};
};
//Example:
var time = new TimeCapture();
//begin tracking time
time.start();
//...do stuff
time.check('say something here')//look at your console for output
//..do more stuff
time.check('say something else')//look at your console for output
//..do more stuff
time.check('say something else one more time')//look at your console for output
I use a really easy function to provide time elapsed in this format: hh/mm/ss
onclick/onfocus/etc..
var start_time = new Date();
on leaving:
var end_time = new Date();
var elapsed_ms = end_time - start_time;
var seconds = Math.round(elapsed_ms / 1000);
var minutes = Math.round(seconds / 60);
var hours = Math.round(minutes / 60);
var sec = TrimSecondsMinutes(seconds);
var min = TrimSecondsMinutes(minutes);
function TrimSecondsMinutes(elapsed) {
if (elapsed >= 60)
return TrimSecondsMinutes(elapsed - 60);
return elapsed;
}
Javascript console internally has a function called "console.time() and console.timeEnd() to do the same. Simple you can use them
console.time("List API");
setTimeout(()=> {
console.timeEnd("List API");
},5000);
More details can be found here
https://developer.mozilla.org/en-US/docs/Web/API/Console/time
I created an ES6 class based on #Shawn Dotey's answer.
The check() method does not log a message, but returns the elapsed time.
The method start() is not needed in his example (the constructor already "starts" it). So I replaced it by reset() which makes more sense.
export default class TimeCapture
{
constructor()
{
this.reset();
}
reset()
{
this.startTime = new Date().getTime();
this.lastTime = this.startTime;
this.nowTime = this.startTime;
}
check()
{
this.nowTime = new Date().getTime();
const elapsed = this.nowTime - this.lastTime;
this.lastTime = this.nowTime;
return elapsed;
}
}
Use it in your project like this:
import TimeCapture from './time-capture';
const timeCapture = new TimeCapture();
setTimeout(function() {
console.log( timeCapture.check() + " ms have elapsed" ); //~100 ms have elapsed
timeCapture.reset();
setTimeout(function() {
console.log( timeCapture.check() + " ms have elapsed" ); //~200 ms have elapsed
}, 200);
}, 100);