Execute a javascript code only on refreshing a page after 10 seconds?

213 views Asked by At

I have a requirement where a java script code is there which makes a ajax call and save the user log in database on page load. But the problem is that every time when the user refresh the page the code is getting executed. I want to execute the statement only if the page is refreshed after 10 seconds not on every page refresh. I have to stop executing the code flow if the page is refreshed before 10 seconds.

2

There are 2 answers

1
Jonas Wilms On BEST ANSWER

This code executes all 10 seconds (or longer), triggered by a page reload:

You need to store the time (in localStorage), on reload check if now is later than stored time+ 10 seconds:

function store(){
//store time:
now=new Date().getTime();
localStorage.setItem("stored",now);
//your password storing
}

window.onload=function(){
now=new Date.getTime();
if(!localStorage.getItem("stored")){
//no time stored, so lets store
store();
return;
}
last=localStorage.getItem("stored");
//if now is later than last+10seconds
if(now>last+1000*60*10){
store();
}
}
0
TVA van Hesteren On

Can you set cookies? Set the cookie value to current path, on redirect check the cookie value against the current URL. When it matches (so it is a refresh) you can trigger your 10 sec delay by

Logging = setTimout(function() {
    Alert("10 seconds passed");
    }, 10 * 1000);

To clear the timeout, use

clearTimeout(Logging)