Fire javascript function 2 sec after no activity in input tag

Is it possible to check if a user has not typed in a text <input/> tag in more than two seconds using javascript?

<input type="text" onKeyUp="check_last_active()" />

The function should trigger something (an alert) only 2 seconds after the user's last input in the <input/> tag, thereby resetting any previous timer functions.

Answers


var timer;
function onInput() {
    clearTimeout(timer);
    timer = setTimeout(functionToRunAfter2Seconds.bind(this), 2000);
}

inputElement.addEventListener('input', onInput, false);

The input event is for input elements and textarea elements (assumed you were using one).

You need to clear the timeout so that if they start typing again you reset the timer.

if you want the jQuery way....

$('#idOfInputOrTextarea').on('input', onInput);

Need Your Help

Alarm "cancel" button not working correctly

android alarmmanager android-pendingintent android-alarms

I have 2 buttons save and set alarm and cancel alarm which are meant to do exactly what they suggest.