How to detect idle time in JavaScript elegantly?

前端 未结 30 2784
别跟我提以往
别跟我提以往 2020-11-21 11:51

Is it possible to detect \"idle\" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.

Idle time:

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 12:52

    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:

    const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
    timer.activate();
    

    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.

提交回复
热议问题