The user opens the site. starts a script that checks the timestamp in localStorage
at a certain interval. If a certain amount of time has passed ( oldDate - currentDate > pullDelay
), then the script changes the timestamp to the current one.
<!DOCTYPE html> <head></head> <body> <script> var pullDelay = 20000; setInterval(function () { var date = localStorage.date; if (date) { var currentDate = new Date(); var oldDate = new Date(date); var diff = currentDate.getTime() - oldDate.getTime(); if (diff < pullDelay) { console.log("Данные свежие"); } else { console.log("Данные устарели"); localStorage.date = currentDate; } console.log("oldDate:" + oldDate.getMinutes() + ":" + oldDate.getSeconds()); console.log("currentDate:" + currentDate.getMinutes() + ":" + currentDate.getSeconds()); } else { localStorage.date = new Date(); } }, pullDelay); </script> </body> </html>
The following behavior was expected, open the first tab, the script sets the timestamp, and then each time writes that the data is outdated and changes the timestamp. And if you open the second tab (it is assumed that at the moment of opening the second tab, the data will be fresh), then the script will always output that the data is fresh.
Current behavior:
The first tab works as expected, but the second one only writes for the first time that the data is fresh, and then constantly writes that the data is out of date, and the time stamp always has the meaning that this tab sets. That is, when the first tab sets a new timestamp value, the second one does not see it and returns a value that it has previously set.
Logs:
1st tab:
Данные устарели oldDate:49:29 currentDate:49:49 Данные устарели oldDate:49:49 currentDate:50:9 Данные устарели oldDate:50:9 currentDate:50:29
2nd tab:
Данные устарели oldDate:49:29 currentDate:49:53 Данные устарели oldDate:49:53 currentDate:50:13 Данные устарели oldDate:50:13 currentDate:50:33