I have a big problem with time lag in setTimeout function. I've created code for button show action and I need do that on certain hour. My problem is that when someone open page about 30 min - 120 min before action without refresh, javascript will do time lag and my action starts much to late.
I need to show that button in very accurate time for everyone - this is reason why I'm using server time (via php) to run script.
Did anyone know how to modify this script to eliminate risk of not showing or to late showing button?
I read about setTimeout
function lag and I am searching solution for my problem.
I need also to mention that I cant ask server everytime beacause I am expecting about 20k - 30k people online on this event - I've tested that, severs will not survive so many php queries.
My code below:
(function getTime() {
$.ajax({
type : 'POST',
async: false,
url : 'time.php',
success : function(response){
// date of button display
var year = "2017",
month = "03",
day = "10",
hour = "14",
minute = "21",
second = "21";
var startDate = new Date("" + year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second +"+01:00");
// +01:00 timezone correction
var buttonTime = startDate.getTime() / 1000; // time - when display button
var currentTime = response;
(function testTime() {
var diff = buttonTime - currentTime;
if (currentTime > buttonTime ) {
// triggers here"
alert(' here will be trigger of show button');
}
if (currentTime <= buttonTime && diff <= 60 ) {
// test after 1 s.
var testDelay = 1000;
currentTime = parseInt(currentTime) + 1;
console.log(currentTime);
setTimeout(function() {
testTime();
}, testDelay);
}
if (currentTime < buttonTime && diff > 60 ) {
// test after 10s.
var testDelay = 10000;
currentTime = parseInt(currentTime) + 10;
console.log(currentTime);
setTimeout(function() {
testTime();
}, testDelay);
}
})();
},
complete(){},
error(){}
});
})();
and php for this:
<?php
$timestamp = time();
echo $timestamp;
?>