Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
Idle time: Period of user inactivity or without any CPU usage
Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
Idle time: Period of user inactivity or without any CPU usage
Improving on Equiman's answer:
.
Apart from the improvements regarding activity detection, and the change from
document
towindow
, this script actually calls the function, rather than letting it sit idle by.It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.
I wrote a simple jQuery plugin that will do what you are looking for.
https://github.com/afklondon/jquery.inactivity
The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.
Hope this helps :)
I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:
It does not depend on jQuery, though you might need to run it through Babel to support older browsers.
https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096
I might release it as an npm package once I get some feedback.
If you are targeting a supported browser (Chrome or Firefox as of December 2018) you can experiment with the requestIdleCallback and include the requestIdleCallback shim for unsupported browsers.
For other users with the same problem. Here is a function i just made up.
It does NOT run on every mouse movement the user makes, or clears a timer every time the mouse moves.
Try this its work perfect..