How to detect idle time in JavaScript elegantly?

前端 未结 30 2767
别跟我提以往
别跟我提以往 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:37

    Here is an AngularJS service for accomplishing in Angular.

    /* Tracks now long a user has been idle.  secondsIdle can be polled 
       at any time to know how long user has been idle. */
    fuelServices.factory('idleChecker',['$interval', function($interval){
        var self = {
            secondsIdle: 0,
            init: function(){
                $(document).mousemove(function (e) {
                    self.secondsIdle = 0;
                });
                $(document).keypress(function (e) {
                    self.secondsIdle = 0;
                });
                $interval(function(){
                    self.secondsIdle += 1;
                }, 1000)
            }
        }
        return self;
    }]);
    

    Keep in mind this idle checker will run for all routes, so it should be initialized in .run() on load of the angular app. Then you can use idleChecker.secondsIdle inside each route.

    myApp.run(['idleChecker',function(idleChecker){
        idleChecker.init();
    }]);
    

提交回复
热议问题