您好,我正在尝试跟踪用户在网页上花费的时间。所以我编写了以下 JavaScript 来执行此操作。
脚本开始跟踪窗口获得焦点的时间,然后在用户移动到其他选项卡或最小化窗口时暂停。
下面是代码:
$(function(){
var count = 0;
var interval;
var ispaused=false;
function setPause(){
ispaused=true;
}
function unpause(){
ispaused=false;
}
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
setPause();
clearInterval(interval);
break;
case "focus":
unpause();
var interval = setInterval(
function(){
if(!ispaused) {
$('#timer').text(count += 1);
}
},1000
);
break;
}
}
$(this).data("prevType", e.type);
});
});
计时器在您聚焦区域时开始,在模糊时暂停,但在每次聚焦和模糊循环后计时器会变得更快。不知道为什么会发生这种情况。请帮忙!
最佳答案
我检查了您提供的 fiddle ,发现您将间隔变量存储在局部变量上,我尝试解决问题以查看它是否正常工作,并在此处更新了 fiddle :
http://jsfiddle.net/9fzd1dap/1/
这是更新后的脚本
$(function () {
var count = 0;
var interval; //This is the global interval variable
var ispaused = false;
function setPause() {
ispaused = true;
}
function unpause() {
ispaused = false;
}
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
setPause();
break;
case "focus":
unpause();
clearInterval(interval);
//I removed the var keyword from the line below to prevent dual declarations.
interval = setInterval(
function () {
if (!ispaused) {
$('#timer').text(count += 1);
}
}, 1000
);
break;
}
}
$(this).data("prevType", e.type);
});
});
发生的情况是,全局间隔变量没有被填充,而局部间隔(函数内部)变量被填充。我已经在更新的 fiddle 上测试过它,似乎工作正常;)
关于javascript - 每次循环后 setInterval 时间都会变快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31874061/