Javascript/Jquery Refresh timer - javascript

I have a simple system that refreshes a div every few seconds:
$(document).ready(function() {
$("#nownext").load("response.php");
var refreshId = setInterval(function() {
$("#nownext").load('response.php?randval='+ Math.random());
}, 20000);
});
Now, because of what the content is, it is more likely to update on the hour, or at half past. (Though not always). What I'd like to do it make the system refresh MORE often between a few minutes before and after the hour (and half past), just to make it more precise.
Is this possible/how would I do it without stressing out the client's computer too much?

Use setTimeout instead of setInterval so you can dynamically alter the timing of the next interval. I'm not sure what the performance implications of creating and checking the Date() object ever millisec in the "Fast" period would be, but you could always tune that frequency up closer to every second if its an issue.
start_timer = function(timing) {
var timer, d = new Date(), min = d.getMinutes(),
timeout = 20000; /* slow timeout */
if((min >= 28 && min <= 30) || min >= 58) {
timeout = 100; /* fast timeout */
}
timer = setTimeout(start_timer, timeout);
// Call your code here.
};
$(document).ready(function() {
start_timer();
});

Since the interval itself is going to be dynamic, you're going to have to use setTimeout instead.
Something like this (untested):
$(document).ready(function() {
$("#nownext").load('response.php?randval='+ Math.random());
var minutes = new Date().getMinutes(), interval = 60*10*1000; // default 10 mins
if (minutes <= 10 || (minutes > 30 && minutes < 35) || minutes > 50) {
// update once-per-minute if within the first/last 10mins of the hour, or 5mins within the half hour
interval = 60*1000;
}
setTimeout(arguments.callee, interval);
});

Related

How can I send messages at regular intervals? [duplicate]

I am trying to update information from a weather service on my page. The info should be updated every hour on the hour. How exactly do I go about calling a function on the hour every hour?
I kind of had an idea but I'm not sure of how to actually refine it so it works...
What I had in mind was something like creating an if statement, such as: (pseudo code)
//get the mins of the current time
var mins = datetime.mins();
if(mins == "00"){
function();
}
You want to check out setInterval: https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
It's a little hard to tell what you're trying to call with your code, but it would be something in the form of:
function callEveryHour() {
setInterval(yourFunction, 1000 * 60 * 60);
}
If you want it every hour, try something like:
var nextDate = new Date();
if (nextDate.getMinutes() === 0) { // You can check for seconds here too
callEveryHour()
} else {
nextDate.setHours(nextDate.getHours() + 1);
nextDate.setMinutes(0);
nextDate.setSeconds(0);// I wouldn't do milliseconds too ;)
var difference = nextDate - new Date();
setTimeout(callEveryHour, difference);
}
Now, this implementation checks the time once, sets the delay (or calls the function immediately), and then relies on setInterval to keep track after that. An alternative approach may be to poll the time every x many seconds/minutes, and fire it .getMinutes() == 0 instead (similar to the first part of the if-statement), which may sacrifice (marginal) performance for (marginal) accuracy. Depending on your exact needs, I would play around with both solutions.
Here is what should work (JSFiddle):
function tick() {
//get the mins of the current time
var mins = new Date().getMinutes();
if (mins == "00") {
alert('Do stuff');
}
console.log('Tick ' + mins);
}
setInterval(tick, 1000);
What you probably want is something like that:
var now = new Date();
var delay = 60 * 60 * 1000; // 1 hour in msec
var start = delay - (now.getMinutes() * 60 + now.getSeconds()) * 1000 + now.getMilliseconds();
setTimeout(function doSomething() {
// do the operation
// ... your code here...
// schedule the next tick
setTimeout(doSomething, delay);
}, start);
So basically the first time the user get the access, you need to know what is the delay in millisecond to the next "hour". So, if the user access to the page at 8:54 (with 56 seconds and 123 milliseconds), you have to schedule the first execution after around 3 minutes: after the first one is done, you can call it every "hour" (60 * 60 * 1000).
Repeat at specific minute past the hour
This counter is a little bit more versatile; it allows to perform a task repeatedly always at the same minute past the hour (e.g. 37 minutes past the hour), and this with up to millisecond precision.
The precision of this timer is derived from its recursion.
At every recursion, the millisecond time to the next minute gets recalculated. This prevents time lag over long periods.
The % sign refers to the modulo operator.
function minuteCount(minutesAfterHour) {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const milliseconds = now.getMilliseconds();
waitUntilNextMinute = setTimeout(minuteCount, 60000 - seconds * 1000 - milliseconds);
if(minutes % 60 === minutesAfterHour) {
doSomethingHourly();
}
}
minuteCount(37);
Finally, timers are best kept away from the main thread. They are best run from within a web worker, as explained here.
This works perfectly with unfocused tabs in desktop browsers.
However, dedicated web workers on Chrome for Android are put to sleep about 5 minutes after moving the main client to the background.
EDIT: Oops, I didn't see the " o' clock" things, so I edit my answer :
var last_execution = new Date().getTime();
function doSomething(force){
var current_time = new Date().getTime();
if (force || (current_time.getMinutes() == 0)
{
last_execution = current_time;
// something
// ...
}
setTimeout(doSomething(false), 1000);
}
// force the first time
doSomething(true);
// ... call your func now
let intervalId;
let timeoutId = setTimeout(() => {
// ... call your func on end of current hour
intervalId = setInterval(() => {
// ... call your func on end of each next hours
}, 3600000);
}, ((60 − moment().minutes()) × 60 × 1000) - (moment().second() * 1000));
Here is my pair of setIntervalWithDelay and clearIntervalWithDelay that one can use like this:
let descriptor = setIntervalWithDelay(callback, 60 * 60 * 1000, nextHourDelay)
And when you are done with it:
clearIntervalWithDelay(descriptor)
Here is my implementation of the functions:
const setIntervalWithDelay = (callback, interval, delay = 0) => {
let descriptor = {}
descriptor.timeoutId = setTimeout(() => {
if(!descriptor.timeoutId){
return
}
descriptor.timeoutId = null
callback()
descriptor.intervalId = setInterval(callback, interval)
}, delay)
return descriptor
}
export const clearIntervalWithDelay = (descriptor) => {
if(!isObject(descriptor) || (!descriptor.timeoutId && !descriptor.intervalId)){
console.warn("clearIntervalWithDelay: Incorrect descriptor. Please pass an object returned by setIntervalWithDelay. Skipping this call.")
return
}
if(descriptor.timeoutId){
clearTimeout(descriptor.timeoutId)
descriptor.timeoutId = null
console.log("clearIntervalWithDelay: stopped during delay.")
}
if(descriptor.intervalId){
clearInterval(descriptor.intervalId)
descriptor.intervalId = null
console.log("clearIntervalWithDelay: stopped during interval repeat.")
}
}
One example of using dayjs to get the delay for the next hour:
let nextHour = dayjs().second(0).millisecond(0).add(1, "hour")
let nextHourDelay = nextHour.diff(dayjs())

JS code to refresh a page at the minute 50 of every hour

I have the following code that will refresh the "updt" page at the minute "50" of every hour.
It only works if I refresh the page manually. How can I modify the code to sense that the minute 50 has come.
function show_hide_me () {
var myDate = new Date();
var mins = myDate.getMinutes();
if (mins == 50){
doSomething();
}
}
function doSomething() {
alert("Page will refresh now");
document.getElementById("updt").click();
}
what you are missing is that you need to check if its 50th minute, every minute.
setInterval(function(){
show_hide_me();
}, 60*1000);
This will run your function every 60000 miliseconds i.e. one minute.
https://www.w3schools.com/jsref/met_win_setinterval.asp
As other users said, what you need is a loop and a method like window.reload(true) or window.location.href = location.href to be executed when mins == 50.
For example, use setInterval:
let intervalId = window.setInterval(function() {
let myDate = new Date();
let mins = myDate.getMinutes();
if (mins == 50){
window.location.href = location.href;
}
}, 60 * 1000); // every 60 seconds
All you have to do is wrap your function in a
setInterval
So that it can be executed maybe ever minute and would continuously check if it's 50minutes into an hour already.
A sample code would be:
setInterval(show_hide_me, 60000)
The reason for this is if the user happens to refresh the page, our checker would always execute our checker.
I think you should change your doSomething function to something like:
function doSomething() {
window.location = window.location.href;
}
Try this logic. This will refresh the page at the 50th minute for every hour.
(function() {
var time = 49 - (new Date()).getMinutes();
time = time >= 0 ? time : (50 + (10 + time));
console.log("Loaded : ", time);
setTimeout(function() {
window.location.reload();
}, time*60000);
})()

How to tween a timestamp to a specific time

I have a fake clock on screen with a time of day:
<div class="time">9:14<sup>am</sup></div>
I want to make a function to be able to tween that time to another arbitrary time,
so that the clock would actually progress through the seconds and hours until it hit the new time(pseudocode):
var currentTime = {
time: 9:14am
}
function changeTime(newTime){
TweenMax.to(currentTime,.5,{
time: newTime
});
}
changeTime(12:32pm);
So in the case above, the minutes would go up by one until they hit 60, then increment the hours by one and reset to zero, then increment again to 60, etc, until they hit 12:32 (with the am switching to pm at 12:00pm).
Is there a way to do this with tweenmax and a timestamp? Or would I need to construct a custom function? Or perhaps is there a better way to tween time?
You can use something like this (and improve it, I did this quickly).
<script>
var hour, minute, second, meridian, isAm;
isAm = true;
hour = 0;
minute = 0;
second = 0;
function timerLoop () {
second++;
if(second > 59) {
second = 0;
minute++;
}
if(minute > 59) {
minute = 0;
hour++;
}
if(hour >12) {
hour = 1;
isAm = !isAm;
}
// update labels
meridian = 'a.m.';
if(!isAm) meridian = 'p.m.';
console.log(hour + ':' + minute + ':' + second + ' ' + meridian);
setTimeout(function() {
timerLoop();
}, 1000);
}
timerLoop();
</script>
I tested it for 2 mins only but the that part was working.
You'll probably want to add leading zero's to the single digits as I haven't done that. And once it is running as you want you can look at adding animations or fades to style it a bit better.

How to add milliseconds to this javascript reverse count down timer counter

numberOfSeconds=1*60,
r=document.getElementById('clock');
var t = setInterval(function(){
numberOfSeconds--;
var minutes=Math.floor(numberOfSeconds/60),seconds=(numberOfSeconds%60)+'';
r.textContent='Registration closes in '+minutes+':'+(seconds.length>1?'':'0')+seconds;
if (numberOfSeconds <= 0) {
clearInterval(t);
alert('boom');
}
},1000);
html section
<div id="clock"></div>
how i can add milliseconds to this reverse count down timer/counter script.
i want it like 00:00:00 <== milliseconds in last.
}},1000 / 20);
However above little change in last of script made seconds into milliseconds but i can't figure out how i can adjust it with seconds like MM:SS:MS 00:00:00
Any Help will be appreciated..!
That setInterval will have to be set to 1 (ms), if you need to see the milliseconds. 1000ms = 1s. So I believe MM:SS:MS would look more like 00:00:000.
I do not think it's possible. i did a test and the results show that js cannot be as fast to set 1millisecond to setInterval. setting it to 1ms - 15ms will output the same results.
normaly the code below should work the way you wanted.
var m = 60*1000, r = document.getElementById("clock");
var t = setInterval(function () {
m--;
var min = Math.floor(m / 60000),
sec = Math.floor((m % 60000) / 1000);
mil = (m % 60000) % 1000; r.innerHTML = min + ":" + sec + ":" + mil;}, 1)
Maybe the problem comes from my computer (maybe it is slow).
if you ever want the test script, tell it in comment so i will give it to you in order you'll test it by yourself

A Better (Hopefully) JavaScript Countdown Timer

In our application, we have a need for a robust countdown timer. When the timer counts down to zero, we move the user on to the next page.
There are a LOT of questions on here about making a countdown timer in JavaScript. I've weeded through a lot of them, looked at a lot of the code samples, tried a lot of plugins, and all of them fail for this one test case: If you adjust your computers system clock, all of these timers mess up (gain time, lose time, or just freeze). The reason is that most of them base their logic on saving some initial start time and then at some interval (either via setTimeout or setInterval) getting the current time and doing a diff between it and the start time. When you adjust your system time, the "current" time can be an hour or days before your start time, or hours or days later.
So, I've come up with the following code to try to handle these system change scenarios. The main thing I do is check if the "diff" between my start and current is negative (or greater than roughly one hour to handle an automatic daylight savings adjustment) to just use the tick interval as an approximation. Also, reset the start time to be current time on each tick, so that elapsed time is the sum of the time between differences, not just the diff between an initial start time and current time. Anyone see any flaws with this approach?
var timeLeft = 60000, // time left in ms, 1 minute for this example
startTime,
totalElapsedTime = 0,
TICK_INTERVAL = 500; // the setTimeout interval
var timerTick = function () {
var now = new Date(),
elapsedTime = now.getTime() - startTime.getTime();
// if the elapsed time was positive and less than approximately an hour, then add the elapsed time to the total
// otherwise, add the TICK_INTERVAL, which we know is the theoretical minimum between timerTick() calls
totalElapsedTime = (elapsedTime > 0 && elapsedTime < 3590000) ? totalElapsedTime + elapsedTime : totalElapsedTime + TICK_INTERVAL;
// reset start time
startTime = now;
// there is time left, so set up another tick
if (totalElapsedTime < timeLeft) {
// update the html that is displaying remaining time
setTimeout(timerTick, TICK_INTERVAL);
}
else {
// time ran out, so do whatever you do when it runs out
}
}
// start the timer
startTime = new Date();
setTimeout(timerTick, TICK_INTERVAL);
Why does the following not work for you?
var timeleft = 60000,
tick = 1000,
intervalID = window.setInterval(function () {
timeleft = timeleft - tick;
if (timeleft <= 0) {
// clear the interval
clearInterval(intervalID);
// do something
}
}, tick);
Update
Using setTimeout (this will drift, but probably be ok unless you are using it for animation):
var timeleft = 60000,
tick = 1000;
window.setTimeout(function timerFn() {
timeleft = timeleft - tick;
if (timeleft > 0) {
// set the next timeout
setTimeout(timerFn, tick);
} else {
// do something
}
}, tick);

Categories

Resources