Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - detect no action for 'x' minutes and run function on that event (no event in X minutes)

Tags:

jquery

How to detect that user have done nothing for 'X' minute and run function on this event?

E.G.

if( // no action from user for 'X' minutes) { //do stuff } ??

Any suggestion much appreciated.

like image 863
Iladarsda Avatar asked Aug 11 '11 13:08

Iladarsda


People also ask

How call a function in jQuery every minute?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

Does jQuery have action after time?

Answer: Use the jQuery delay() method You can use the jQuery delay() method to call a function after waiting for some time. Simply pass an integer value to this function to set the time interval for the delay in milliseconds.

How to delay function in jQuery?

The delay() is an inbuilt method in jQuery which is used to set a timer to delay the execution of the next item in the queue. para1: It specifies the speed of the delay. para2: It is optional and specifies the name of the queue.


1 Answers

Live Demo

Like everyone else has stated use setTimeout and set it to the desired amount of time to wait. If there is any activity just clear the timeout using clearTimeout.

// If theres no activity for 5 seconds do something
var activityTimeout = setTimeout(inActive, 5000);

function resetActive(){
    $(document.body).attr('class', 'active');
    clearTimeout(activityTimeout);
    activityTimeout = setTimeout(inActive, 5000);
}

// No activity do something.
function inActive(){
    $(document.body).attr('class', 'inactive');
}

// Check for mousemove, could add other events here such as checking for key presses ect.
$(document).bind('mousemove', function(){resetActive()});
like image 68
Loktar Avatar answered Oct 24 '22 23:10

Loktar