简体   繁体   中英

setTimeout for whole site, not just one page

How would I use setTimeout() - or any other javascript method - to call a function when the user had been on my website for 45 seconds.

I was using the below:

setTimeout(function(){ ....code.... }, 45000);

But if the user navigated off the page and onto another page on the site before 45 seconds, the timer was reset.

I'd like the setTimeout to apply to the time the user landed on the first page, regardless of what page they are on now.

I will be including this javascript on every page on the site.

Thanks.

You have to store the timestamp to localStorage when user comes to your page and start a timer using setTimeOut and listen to onbeforeUnlaod event when user goes from your site.

Again when user comes back query the localStorage for lastTime and reinit the timer.

Here is a fiddle

var your_delay = 5*1000;
window.init= function(){
    var start = localStorage.getItem('start');
    var end = new Date().getTime();
    if(start){
         if(end-start<your_delay)
           setTimeout(action,your_delay-(end-start));
    }else{
       setTimeout(action,your_delay);
    }
}
window.onbeforeunlaod = function(){
      /* Send the timer to server if you want it to be consistant across browser */
}


window.action = function(){
     alert("Hi");
}

init();

Just add that javascript file to all the pages with the setTimeout function. It will reset automatically when the user goes to other pages:

setTimeout(() => { ... }, 45e3)

If I understood correctly you also want to save the time IF the user is more than 45 seconds on the page. Then use localStorage for that. First get the time he has been on the site with a date object:

let timer = new Date()

Then save the difference on localStorage (in milliseconds):

localStorage.setItem("Time on site", new Date().getTime() - timer.getTime())

Whenever you want to access that time use:

localStorage.getItem("Time on site")

Execute the timer when the page loads inside:

let timer
window.addEventListener('load', () => {
    timer = new Date()
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM