Timer is resetting on refresh how to avoid that? - javascript

this is my java-script code which is resetting on refreshing how to avoid that
<script>
//define your time in second
var c=120;
var t;
timedCount();
function timedCount()
{
var hours = parseInt( c / 3600 ) % 24;
var minutes = parseInt( c / 60 ) % 60;
var seconds = c % 60;
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
document.getElementById("timer").innerHTML=result;
if(c == 0 )
{
//setConfirmUnload(false);
//$("#quiz_form").submit();
window.location="result.php?td=$tid";
}
c = c - 1;
t = setTimeout(function()
{
timedCount()
},
1000);
}
</script>

Whenever a page is readloaded, the entire context of the old page is destroyed and an entirely new context is created. You can't keep a timer from one page load running on the next page load.
If you need to save some state from one page load to the next and then in the next page load examine that state and decide exactly how to set up the initial page to match what was previously going on, then you can save state between page loads in either HTML5 local storage or in a cookie.
The other possibility is to NOT reload your page and instead update the contents of the page dynamically using ajax and javascript. That way your existing timer would just keep running because there would be no page reload at all.
If all you're trying to do with your timer is show how much time is left in some countdown, you can set the countdown zero time into HTML5 local storage and when the reloaded page loads, it can check the time set in local storage and start the countdown timer to match the time it was previously set for.
Use cookie, or if HTML5 then local/session storage to save state.
HTML
Save Current Time |
Retrieve Saved Time
<div id="result"></div>
JAVASCRIPT
function SaveTime(){
var date = new Date();
var timeObj = { sec:date.getSeconds(), min:date.getMinutes(), hr:date.getHours() };
localStorage.setItem("timeObj", JSON.stringify(timeObj));
$('#result').append(JSON.stringify(timeObj)+' -- > Saved<br />' );
}
function retrieveTime(){
var timeObj = JSON.parse(localStorage.getItem("timeObj"));
//You have the time with you now
//You have the time with you now
$('#result').append(timeObj.hr+':'+timeObj.min+':'+timeObj.sec+' --> Retrieved<br />');
}
Its just a basic example to save timer in local storage on click. Modify it and call the javascript function in timer regularly.

Related

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.

Detect Five Minute Mark

We use a graphing system that uses SNMP to retrieve data to graph with on every five minute mark. For example, 12:00, 12:05, 12:10, and so on. We retrieve the graph as an image. The problem is that the browser likes to use the cached image, and we cannot get a new image until we delete the cache. What I am trying to do is generate a random tag to append to the image that makes it unique, therefore not using the cached image. We were able to generate a random tag every time the image was retrieved, but this led to a lot of server utilization from all the requests and slower response times. What I am attempting to do now is generate a new tag ONLY if:
a) it has been greater than four minutes (5+) since the user retrieved an image (because a five minute mark would have had to pass),
b) it has been less than five minutes since an image was retrieved, but a five minute mark has passed since the last time an image was retrieved. For example, a if a person retrieves an image at 12:04, he or she won't be able to get a new one until five minutes later with the first test, but the second test will recognize that 12:05 passed if he or she attempts to retrieve an image at 12:06.
What I tried to do was use a cookie and set the cookie to the new tag every time a new tag was generated. On page load it would load RandomTag variable with the value of the cookie. Onclick it would be determined if five minutes has passed since the time in the RandomTag variable or if a five minute mark has past since the last generation of a tag, generate a new tag if it has, and set cookie with new tag; otherwise the tag would go unchanged.
Could anyone check this and see if there are any problems? I tried this code, and it made my page hang. I don't know what I am missing. Also, if you have a simpler way to do this, please let me know.
Here is an example of my code:
<body onload="checkCookie()">
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function checkCookie() {
randomTag = getCookie("timeTag");
}
function tagGet() {
timeNow = new Date().getTime();
timeDif = timeNow - randomTag;
minNow = timeNow.getMinutes();
minLast = randomTag.getMinutes();
minDif = minNow - minLast;
if (timeDif > 29999) { //If 5+ minutes have passed
randomTag = timeNow;
setCookie("timeTag", timeNow, 365);
}
else if (timeDif < 30000) { //If less than 5 minutes have passed
if (minDif > 0) { //If at least 1 minute has passed since last random tag generation
for (y = 0; y < minDif; y++) { //Check to see if a five minute mark has passed by decrementing the current minute mark and comparing it to a five minute mark
for (z = 0; z < 60; z += 5) { //Increment by five minute marks for comparison ... 0, 5, 10, etc
if (minNow == z) { //If the minute mark now matches a five minute mark
randomTag = timeNow;
setCookie("timeTag", timeNow, 365);
}
minNow--; //Decrement minute mark now for comparing next minute mark
}
}
}
}
}
# //This is generic
Set a global variable lastImage and set that to Date() when an image is requested.
Then only retrieve a new image if Date() >= lastImage + (5 * 60 * 1000).
And you can use Date() at the end of the url for the unique identifier to avoid caching.
Ok. I found a VERY simple solution to this. Basically I will just set my variable to equal the last five minute mark by rounding the current time down to the last five minute mark! Silly me. The answer was here, except I subtracted 2.5 instead of added 2.5 since I want to find the last five minute mark: Javascript: Round Time UP nearest 5 minutes

Automatically play a video on my site at a certain time of day

Context: A video on an html page.
I have a hidden video on an html page.
I'd like the video to appear (and autoplay) daily at 12:00 noon EST.
Can this be accomplished with JavaScript? Where should I start?
Any feedback is appreciated.
var targetHours = 12;
var targetMinutes = 0;
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var minutesLeft = (60*24 + (targetHours - hours)*60 + targetMinutes - minutes) % (60*24);
setInterval(function () {alert("Hello")}, minutesLeft * (60*1000))
This doesn't need to check every second like the solution of #Burrito. If you want it to trigger every 24hours (if someone leaves the page open for so long), set the timer again in the called function with a 24h timeout.
I would have a DOM element as a placeholder (either a image or the paused video) by using the date object in a loop you can then fire the HTML5 video by
document.getElementById('video_id').play();
so something like
function checkTimeAndPlay() {
var date = new Date();
if (date.getHours() == 12 && date.getMinutes() == 0) {
document.getElementById('video_id').play();
} else {
setTimeout("checkTimeAndPlay", 1000);
}
}
I'd advise you to look into the JavaScript Date object which gives you access to the current time and a whole lot more.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

JS call function every 5 mins count of server time

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

Categories

Resources