0

How to delay the .keyup() handler until the user stops typing in JavaScript?

function delay(callback, ms) {
  var timer = 0;
  return function() {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      callback.apply(context, args);
    }, ms || 0);
  };
}


// Example usage:

$('input').keyup(delay(function (e) {
  console.log('Time elapsed!', this.value);
}, 500));
<input type="text" placeholder="Type something here..."/>
input {
  padding: 10px;
  border: 2px solid #dddddd;
  border-radius: 4px;
}
RUN
add comment
Suggest a different solution or add another example