How to detect idle time in JavaScript elegantly?

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

    Similar to Iconic's solution above (with jQuery custom event)...

    // use jquery-idle-detect.js script below
    $(window).on('idle:start', function(){
      //start your prefetch etc here...
    });
    
    $(window).on('idle:stop', function(){
      //stop your prefetch etc here...
    });
    

    //jquery-idle-detect.js
    (function($,$w){
      // expose configuration option
      // idle is triggered when no events for 2 seconds
      $.idleTimeout = 2000;
    
      // currently in idle state
      var idle = false;
    
      // handle to idle timer for detection
      var idleTimer = null;
    
      //start idle timer and bind events on load (not dom-ready)
      $w.on('load', function(){
        startIdleTimer();
        $w.on('focus resize mousemove keyup', startIdleTimer)
          .on('blur',idleStart) //force idle when in a different tab/window
          ;
      ]);
    
      function startIdleTimer() {
        clearTimeout(idleTimer); //clear prior timer
    
        if (idle) $w.trigger('idle:stop'); //if idle, send stop event
        idle = false; //not idle
    
        var timeout = ~~$.idleTimeout; // option to integer
        if (timeout <= 100) timeout = 100; // min 100ms
        if (timeout > 300000) timeout = 300000; // max 5 minutes
    
        idleTimer = setTimeout(idleStart, timeout); //new timer
      }
    
      function idleStart() {
        if (!idle) $w.trigger('idle:start');
        idle = true;
      }
    
    }(window.jQuery, window.jQuery(window)))
    

提交回复
热议问题