JS call function every 5 mins count of server time - javascript

I need to call some JS function every 5 mins, but not simply every 5 mins after page loading, but on every 5 mins of server time. Ie when server clock reaches 5, 10, 15 etc mins.
I wrote next code, but i dont know how to calk timeout to call first function when current server time < %5 minutes (03:13:28 for example)..
First time i call function on page load, but next time it must be called on server time event.
Dig = new Date(parseInt(new Date().getTime()/1000)*1000);
var min = Dig.getMinutes();
var sec = Dig.getSeconds();
if(min%5==0){
var to = ((300-sec)*1000);
}else{
// HERE MY PROBLEM
}
setTimeout(function(){
myFunction();
setInterval(function(){
// do something every 5 mins on server time
myFunction();
}, 300000);
}, to);
Now i do the //PROBLEM place like
var os = 0;
if(min<4){
os = 4-min;
}else if(min<9){
os = 9-min;
}else if(min<14){
os = 14-min;
}else if(min<19){
os = 19-min;
}else if(min<24){
os = 24-min;
}else if(min<29){
os = 29-min;
}else if(min<34){
os = 34-min;
}else if(min<39){
os = 35-min;
}else if(min<44){
os = 44-min;
}else if(min<49){
os = 49-min;
}else if(min<54){
os = 54-min;
}else if(min<59){
os = 59-min;
}
sec = 60-sec;
os = ((os*60)+sec);
var to = (os*1000);
but i need shortest variant.

If your goal is to find out how many milliseconds it is from "now" until the next five-minute mark, here's how you do that:
var fiveMinutes = 5 * 60 * 1000;
var now = new Date().getTime();
var untilNextFiveMinuteMark = fiveMinutes - (now % fiveMinutes);
console.log("now is " + new Date(now));
console.log("time to next five-minute mark: " + untilNextFiveMinuteMark + "ms");
console.log("next five minute mark: " + new Date(now + untilNextFiveMinuteMark));
Live Example | Live Source
For instance, for me right now (I'm in the UK), it says:
now is Sun Feb 02 2014 13:47:36 GMT+0000 (GMT)
time to next five-minute mark: 143169ms
next five minute mark: Sun Feb 02 2014 13:50:00 GMT+0000 (GMT)
In your question, more than once you talk about "server time," but there's nothing in your code doing anything related to the time on the server. It's all using the time on the client. To get the time on the server, you have to have the server send that information to the client and then use it (and even then, of course there will be inaccuracy, as it takes an indeterminate time for the client to retrieve the time value from the server; in normal use, that time will be small).

you can show the timestamp on the page by server side language
<script>
var serverTimeStamp = <?php echo (1000*time());?>;
</script>
and you will have a actual server time value on this particular page.
Also you can make ajax calls to server, that will return the actual server time,
and perform client site javascript actions when the time have come.

Call every 5 mins on SERVER time
I don't see major differences with every 5 mins on server time and client machine time.
Every 5 minutes is always 5 minutes every where.
There is no need to calculate 5 minutes gap, just set the interval window.setInterval()
SAMPLE Code:
var counter = 0;
CallEvery5Minutes();
var interval = window.setInterval(function () {
CallEvery5Minutes();
}, 5000); //5000 is 5 Seconds
function CallEvery5Minutes() {
console.log("5 Minutes Completed!!! = '" + counter + "'");
if (counter == 5) {
clearInterval(interval);
console.log("Interval has been cleared!!!");
}
counter += 1;
}
Here 5000 is 5 Seconds.
Refer LIVE DEMO

Related

Pop up window on specific time

I'd like to know if there is a way to show scheduled pop up windows, say you're hosting a virtual conference at 6pm, and you want to warn your users an hour early by showing a pop up window at 5pm with a messagge like "Main conference starts in one hour".
This is for a webpage intended to work on desktop and mobile, thus I'm working on HTML and javascript.
Haven't code anything yet, I'm rather looking for a starting point.
Appreciate the help.
So based on what you just said, I think that the following js code will solve your issue, however, since I don't know what is your current environment, you will have to change the code to your needs:
// Always use a 24 hour format with this implementation.
function scheduleDailyConferences(timeArray) {
const offset = 60; // alert offset (1h prior in minutes)
const now = new Date();
const current = now.getHours() * 60 + now.getMinutes();
for (let time of timeArray) {
let tot = time.h * 60 + time.m - offset;
if (tot < current) continue;
tot -= current;
setTimeout(() => {
alert(`Your meeting starts in ${offset} minutes.`);
}, tot * 60 * 1000);
}
}
// assuming the following conferences of the day:
scheduleDailyConferences([
{ h: 13, m: 45 } // 1:45 pm
{ h: 4, m: 00 } // 4:00 pm
]);
Basically, given a time table timeArray in a human readable format, it reads every entry, subtracts a given offset of 1 hour and figures out when to fire an alert.
If the meeting has already ended or begun, it doesn't fire an alert (but you can easily change that).

Reload html page at every tenth minute

I am trying to update a web-page at every tenth minute 7:40...7:50, etc. How do I do this?
Here is my code:
<body onload="checkTime()">
function checkTime(){
var unixTime = Date.now() / 1000;
var partTenMinuteTime = unixTime%600;
var time = unixTime - partTenMinuteTime + 600;
var difference = (time-unixTime)*10000;
console.log(difference);
setInterval(location.reload(),15000)
}
This is all I have, everything else I have tried does not work. I am using location.reload();
My problem is where this function gets called and how to implement it.
Here you can get nearest 10th min
let getRoundedDate = (minutes, d=new Date()) => {
let ms = 1000 * 60 * minutes; // convert minutes to ms
let roundedDate = new Date(Math.round(d.getTime() / ms) * ms);
return roundedDate
}
console.log(getRoundedDate(10))
Now you can use setInterval or in recursive setTimeout
You can get the minutes of the current hour and check how many minutes there are until the next 10-minute mark and use setTimeout. Your updatePage method should also continue to use call itself with setTimeout, if you are using AJAX to refresh the page (which makes more sense than reloading).
function updatePage(){
//update page
setTimeout(updatePage, 10 * 60 * 1000);
}
const now = new Date;
const nextDate = new Date;
nextDate.setFullYear(now.getFullYear());
nextDate.setDate(now.getDate());
nextDate.setMonth(now.getMonth());
nextDate.setHours(now.getHours());
nextDate.setMinutes(Math.ceil(now.getMinutes()/10)*10);
setTimeout(updatePage, nextDate - now);
You were very close with the solution in your question.
A couple of things to note:
You don't need setInterval(), but can use setTimeout() instead. After the page is reloaded, you will get a new timeout.
The callback you pass to setInterval() or setTimeout() needs to be a function and not a function call. If you include a function call, it will be executed immediately and not wait for the timeout or interval.
There is no need to create additional intervals to be able to correctly determine the 10 minute mark, as proposed in other answers to this question. You can correctly determine the correct time to call the reload action by doing the calculation you had in your question.
I'm aware that there are situations where you have too little control over the server code to be able to convert to AJAX, but if possible AJAX or websocket solutions should be preferred over reloading the page.
function reloadAfter(minutes) {
const millisToWait = minutes * 60 * 1000;
const millisLeft = millisToWait - (Date.now() % millisToWait);
setTimeout(() => location.reload(), millisLeft);
}
addEventListener('load', () => reloadAfter(10));
Why reload the page at all? Just use AJAX to query what you need. Here's code you could use to do your AJAX query, or reload the page... the later being a bad practice:
function onTenMin(func){
const m = 600000;
let i = setTimeout(()=>{
func(i); i = setInterval(()=>{
func(i);
}, m);
}, m-Date.now()%m);
}
addEventListener('load', ()=>{
onTenMin(interval=>{ // if you want you can pass the interval here
const dt = new Date;
console.log(dt.toString());
});
}); // end load
Just pass the function you want to onTenMin.
What's happening here?
Date.now() gives you milliseconds since January 1, 1970, 00:00:00 UTC. 600000 milliseconds is 10 minutes. % is the remainder operator, so it gives you the milliseconds remaining after division of the 600000. 600000 minus that remainder gives you how many more milliseconds until the next ten minute time. When that timeout happens it executes the function you pass to func then sets an interval which executes every 600000 milliseconds, passing the interval to func.
You can use a meta refresh instead don't burden the engine with timers
<meta http-equiv="refresh" content="600">
10 minutes = 600 seconds, so... This would automatically refresh your page every 10 minutes exactly.
Update
Every Exact 10th Minute Of An Hour
var tick = 10*60*1000,
tock = tick - Date.now() % tick;
setTimeout( "location.reload()", tock );
var tick = 10 * 60 * 1000,
tock = tick - Date.now() % tick;
setTimeout("location.reload()", tock);
//-----show something on the page----
with(new Date(tock))
document.write("Reloading in: " +
getMinutes() + " min, " +
getSeconds() + " sec, " +
getMilliseconds() + " mil."
);

Multiple timers on a page

I've been given a task to display multiple timers on a page in a table. The start values for these timers are stored in a database and loaded into the view when the page loads.
I initially designed this as a single timer. In that version, using the clearInterval() method to stop the timer from counting down past 0:00 works. With the multiple timers, it does not.
There's no way for me to anticipate how many records are going to display in the table.
The single counter variable was how I implemented this when there was only one timer. That seems to still work to start the countdown process, but doesn't stop it as expected when the clearInterval(counter) is called.
var counter;
// NOTE: Does not support days at this time
// Ex: StartTimer(5, 'm', 'timer') for Five Minutes
// Ex: StartTimer(5, 'h', 'timer') for Five Hours
function StartCountdownTimer(timeDistance, timeMeasurement, timerCallback) {
// Add timeDistance in specified measurement to current time
var countDownDate = moment().add(timeDistance, timeMeasurement).toDate();
var timeRemaining;
counter = setInterval(function () {
// Get Current Time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
let duration = moment.duration(distance * 1000, "milliseconds");
let hours = duration.hours();
let minutes = duration.minutes();
let seconds = duration.seconds();
if (minutes < 10 && hours && hours > 0) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// If the count down is finished clear the counter interval.
if (distance < 0) {
clearInterval(counter);
}
else {
timerCallback(hours, minutes, seconds);
}
}, 1000);
}
I would guess that the clearInterval() is not working because there are multiple timers on the page, but I'm not sure of the best way to load multiple variables and assign them to their own setInterval() function to then leverage when doing the clearInterval() later.
This is a separate JS file that is called by the HTML in the $(document).ready() function.
Any ideas on how to get this clearInterval() to work with multiple timers on a page?
Put the various intervals in an object, with a counter variable that increments every time you assign an interval. Then use the counter as the key and assign its value to the interval.

How to automatically do an AJAX request for PHP script every day at certain time?

I tried to write a code that would everyday at 23:00 make an AJAX request to this URL { url: "addCredits.php" }. At this URL there is SQL code for adding +5 to the "Credit" column by using PHP. I want every user to receive +5 in their "Credit" column everyday.
I tried running the code below, but at 23:00, the user did not receive any credit.
<script>
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
I see a couple of problems here.
Are you sure your users actually had this page and running at 23:00:00? It won't work if the page isn't open, obviously.
getHours (et al) give the time in the user's local time zone. Users in different time zones will have this condition true at different times.
The condition you're using -- h == 23 && m == 00 && s == 00 -- will only be true if the timer fires between 23:00:00 and 23:00:01. Since you're using a 1000 millisecond timer, and JS timers aren't guaranteed to fire on the exact requested interval, it's possible that some users will end up "skipping" the condition if the timer fires at, say, 22:59:59.99 and 23:00:01.00.
Most importantly, though: Using client-side logic for this is completely insecure. Any user can request addCredits.php as many times as they want, whenever they want; the fact that it's normally requested through this Javascript won't stop them from running it other ways. If you want to give your users credits periodically, use a server-side scheduled task to do it.

Node.js scheduling function in conditional statement

I'm working on a project on Node.js. I want to execute some conditional code portion after waiting for five minutes since the last code does. I only need it to run once that way (not everyday or ...). The rest of the code will take over but when it ticks five minute, that will execute. Can I accomplish this?
EDIT: The code from Abdennour TOUMI partially works. But his way of denoting the minute by the variable didn't work for me. So I made the following edit according to the example from the module's page.
var schedule = require('node-schedule');
var AFTER_5_MIN=new Date(new Date(new Date().getTime() + 5*60000))
var date = new Date(AFTER_5_MIN);
var j = schedule.scheduleJob(date, function() {
if(condition1){
// Runned once --> Thus, you need to cancel it
// code here, than code to run once
j.cancel();
}else{
//it will be repeated
}
});
Your mistake is use 5 fields & the right is 6 fields .
* 0 * * * * --> For each hour at the 0 minute of that hour.
To start after 5 minutes , you could calculate the minute of hour after 5 minutes :
var schedule = require('node-schedule');
var AFTER_5_MIN=new Date(new Date(new Date().getTime() + 5*60000)).getMinutes();
var j = schedule.scheduleJob(`* ${AFTER_5_MIN} * * * *`, function() {
if(condition1){
// Runned once --> Thus, you need to cancel it
// code here, than code to run once
j.cancel();
}else{
//it will be repeated
}
});
Is there any reason you can't use setTimeout()?
const WAIT_TIME = (60 * 5) * 1000; //5 Minutes
var timer = setTimeout(function(){
console.log('Cron job works!')
}, WAIT_TIME);
/*
* If conditions change in this five minutes and you need to cancel executing
* the callback above, you can clear the timer
* clearTimeout(timer);
*/

Categories

Resources