Search code examples
javascriptjquerypage-refresh

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


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.


Solution

  • 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();
    }
    }