How to detect idle time in JavaScript elegantly?

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

    As simple as it can get, detect when mouse moves only:

    var idle = false;
    
    document.querySelector('body').addEventListener('mousemove', function(e) {
        if(idle!=false)idle = false;
    });
    
    var idleI = setInterval(function()
    {   
        if(idle == 'inactive')
        {
            return;
        }
    
        if(idle == true)
        {
            idleFunction();
            idle = 'inactive';
            return;
        }
    
        idle = true;
    }, 30000);// half the expected time, idle will trigger after 60s in this case.
    
    function idleFuntion()
    {
       console.log('user is idle');
    }
    

提交回复
热议问题