Home > Net >  Javascript Event Listener when nothing is happening after a period of time
Javascript Event Listener when nothing is happening after a period of time

Time:06-06

I would ask if someone know an Event Listener, that start to work when there aren't pressed button on the Keyboard for a determined period of time, something like that:

document.addEventListener('wait', myFunction);

CodePudding user response:

You can use setTimeout and clearTimeout for this.

setTimeout runs a function after a specified period of time. It also returns an ID that can be passed to clearTimeout.

clearTimeout cancels the timeout associated with the ID that you give it.

You would call setTimeout to start the "idle timer", and store the timer ID in a variable. Then, if the user pressed a key (which you could detect using a keypress event listener) then you would use clearTimeout to cancel the timer (and maybe start it again).

CodePudding user response:

You can find useful answer here : How to detect idle time in JavaScript

You would use the 'keypress' event. So basically create a timeout and reset it every time a key is pressed!

Hope it helps!

  • Related