【问题标题】:jquery timeout function is not being called again after one call to itjquery timeout函数在一次调用后不再被调用
【发布时间】:2017-02-02 15:06:44
【问题描述】:

请帮助我。我必须找到用户在页面上完成活动的总时间。我制作了 jquery 代码,该代码发现如果用户空闲 10 秒,代码会增加其空闲时间。但是此代码的问题是,当用户在该页面上连续闲置(例如 30 秒)时,代码必须添加 10 秒 + 10 秒 +10 秒总共 30 秒的空闲时间。它只增加了 10 秒的空闲时间,跳过了我上面提到的 20 秒的其余部分。虽然当用户在超时后在页面上执行一些活动(如 mousemove 等)时它工作正常,但它再次增加了 10 秒的空闲时间,但这次又只是 10 秒,而不是完整的时间跨度。

问题可能与超时有关。 timeout 函数在一次调用后不再被调用。我认为没有进行连续的超时调用。我不确定。

这里是代码

var timeoutID;	
var start, end, pagefocustime = 0;
var opentime, midtime = 0;
var exacttime = 0;
var inactivetime = 10000, idletime = 0;	
var window_focus = true;
$(document).ready(function() {
  start = performance.now(); //Calculating Startup Time
  midtime = start; 
  
  $(window).on('blur', function() {
	window_focus = false;
    end = performance.now();
    pagefocustime += end - midtime;
	exacttime += end - midtime;
  })

  $(window).on('focus', function() {
	window_focus = true;  
    midtime = performance.now();
  })
  
  if(window_focus){
	function setup() {
		this.addEventListener("mousemove", resetTimer, false);
		this.addEventListener("mousedown", resetTimer, false);
		this.addEventListener("keypress", resetTimer, false);
		this.addEventListener("DOMMouseScroll", resetTimer, false);
		this.addEventListener("mousewheel", resetTimer, false);
		this.addEventListener("touchmove", resetTimer, false);
		this.addEventListener("MSPointerMove", resetTimer, false); 
		startTimer();
	}
	
	setup(); 
	 
	function startTimer() {
		// wait 10 seconds before calling goInactive
		timeoutID = window.setTimeout(goInactive, 10000);
	}
	 
	function resetTimer(e) {
		window.clearTimeout(timeoutID);
	 
		goActive();
	}
	 
	function goInactive() {
		idletime = idletime + inactivetime;
		console.log("I am called");
	}
	 
	function goActive() {      
		startTimer();
	}

  }	
  $(window).on('beforeunload',function(){
    end = performance.now(); 
    pagefocustime += end - midtime; 
    console.log("Total page focus Time : " + pagefocustime);
	opentime = end - start;
	console.log("Total Page Open time : " + opentime);
	exacttime = pagefocustime - idletime;
	console.log("exact time : " + exacttime);
  });             
});

请帮忙。 非常感谢提前

【问题讨论】:

  • 如果您使用的是 jQuery,为什么不使用 $(this).on("mousemove mousedown keypress etc", resetTimer) 而不是对 addEventListener() 进行七个单独的调用?

标签: javascript jquery html timer timeout


【解决方案1】:

您可以在“goInactive”方法中调用“startTimer”来重新开始检查。

当您在该代码中时,您可以将所有这些事件名称放入一个数组中,然后使用 map 函数附加侦听器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多