serkanyersen / ifvisible.js

Crossbrowser & lightweight way to check if user is looking at the page or interacting with it.

Home Page:http://serkanyersen.github.com/ifvisible.js/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Idle fired incorrect

LimbaHub opened this issue · comments

commented

After status changed from active to idle once, idle been fired incorrect.
For example, when i keep moving mouse after status changed from idle to active, idle still fired, even througn my mouse never stopped moving.

I'm experiencing the same issue. It correctly detects activity until the first idle event fires, and at that point the idle event will always fire on its interval, regardless of activity on that page.

I came across the same issue in 1.0.6.

I think it's to do with the wakeUp function defined in trackIdleStatus. When it is called in response to mousemove etc after being idle, it calls ifvisible.wakeup(), which fires the wakeup event, which triggers another call to this function. This is happening after the previous timer has been cleared, and before the new timer is set. I think the second call is overwriting the timer token of the first call without clearing it.

I seem to have fixed this by setting the new timer before triggering the wakeup event.

Old code:

trackIdleStatus = function() {
	var timer, wakeUp;
	timer = false;
	wakeUp = function() {
		clearTimeout(timer);
		if (status !== "active") {
			ifvisible.wakeup();
		}
		idleStartedTime = +(new Date());
		return timer = setTimeout(function() {
			if (status === "active") {
				return ifvisible.idle();
			}
		}, idleTime);
	};
	wakeUp();
	addEvent(doc, "mousemove", wakeUp);
	addEvent(doc, "keyup", wakeUp);
	addEvent(doc, "touchstart", wakeUp);
	addEvent(window, "scroll", wakeUp);
	ifvisible.focus(wakeUp);
	return ifvisible.wakeup(wakeUp);
};

New code:

trackIdleStatus = function() {
	var timer, wakeUp;
	timer = false;
	wakeUp = function() {
		clearTimeout(timer);
		timer = setTimeout(function() {
			if (status === "active") {
				return ifvisible.idle();
			}
		}, idleTime);
		if (status !== "active") {
			ifvisible.wakeup();
		}
		idleStartedTime = +(new Date());
		return timer;
	};
	wakeUp();
	addEvent(doc, "mousemove", wakeUp);
	addEvent(doc, "keyup", wakeUp);
	addEvent(doc, "touchstart", wakeUp);
	addEvent(window, "scroll", wakeUp);
	ifvisible.focus(wakeUp);
	return ifvisible.wakeup(wakeUp);
};

I've updated this library and added tests. If you can reproduce the issue I can help get it fixed. See the new test here: https://github.com/rosskevin/ifvisible/blob/master/src/IfVisible.ts