繁体   English   中英

整个网站的setTimeout,而不仅仅是一页

[英]setTimeout for whole site, not just one page

当用户在我的网站上停留45秒时,我将如何使用setTimeout()或任何其他javascript方法来调用函数。

我正在使用以下内容:

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

但是,如果用户在45秒之前浏览页面并转到网站上的另一页面,则计时器将重置。

我希望将setTimeout应用于用户登陆第一页的时间,而不管他们现在在哪个页面上。

我将在网站的每个页面上包含此javascript。

谢谢。

当用户进入页面时,您必须将时间戳存储到localStorage ,并使用setTimeOut启动计时器,并在用户离开您的站点时监听onbeforeUnlaod事件。

再次当用户回来时,查询localStorage的lastTime并重新初始化计时器。

这是一个小提琴

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

只需使用setTimeout函数将该javascript文件添加到所有页面即可。 当用户转到其他页面时,它将自动重置:

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

如果我理解正确,那么如果用户在页面上的停留时间超过45秒,您还希望节省时间。 然后使用localStorage 首先使用日期对象获取他在网站上的时间:

let timer = new Date()

然后将差异保存在localStorage (以毫秒为单位):

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

每当您想访问该时间时,请使用:

localStorage.getItem("Time on site")

页面加载到内部时执行计时器:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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