JQuery run function on change and on delay

Viewed 119

I found this function to delay a keyup callback, which works perfectly after the 3 seconds I have set it too.

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


$('#postcode').keyup(delay_callback(function (e) {
    do_postcode();
    validate_fields();
}, 3000));

So I also want to call it on change like this $('#postcode').on('change',... but that in addition to the delay makes it run on change and then 3 seconds later so its running twice.

My "onchange" code

$('#postcode').on('change', function(e) {
    e.stopPropagation();
    do_postcode();
    validate_fields();
});

How can I call the function both on change and after the delay, but not both.

So I want to cancel the delay if the input is changed

1 Answers

If i understant your explanation, you want to trap both events but you just want to cancel delay when event change is detected ..

timer = -1;
function delay_callback(callback, ms) {

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

$('#postcode').keyup(delay_callback(function (e) {
    do_postcode();
    validate_fields();
}, 3000));

$('#postcode').on('change', function(e) {
    clearTimeout(timer);
    do_postcode();
    validate_fields();
});

why not replaced keyup event by input event?

$('#postcode').on("input change", function (e) {
  var $this = $(this);
  if(e.type == "change"){
    clearTimeout($this.data('timer'));//if you want to cancel the timeout
    do_postcode();
    validate_fields();
    return;
 }
  
  var delay = 3000; // 3 seconds delay after last input

  clearTimeout($this.data('timer'));
  $this.data('timer', setTimeout(function(){
    do_postcode();
    validate_fields();

  }, delay));
});
Related