Run javascript function when user finishes typing instead of on key up?

So, I’m going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, let’s start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.

Making a few assumptions…

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 seconds for example
var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

Leave a Comment