首页 > 解决方案 > JQuery 在更改和延迟时运行功能

问题描述

我发现这个函数可以延迟 keyup 回调,在我设置它的 3 秒后它也能正常工作。

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));

所以我也想像这样在更改时调用它,$('#postcode').on('change',...但是除了延迟之外,它还使它在更改时运行,然后在 3 秒后运行,所以它运行了两次。

我的“onchange”代码

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

如何在更改时和延迟后调用该函数,但不能同时调用。

所以我想在输入改变时取消延迟

标签: jquery

解决方案


如果我理解您的解释,您想捕获这两个事件,但您只想在检测到事件更改时取消延迟..

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();
});

为什么不用输入事件替换 keyup 事件?

$('#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));
});

推荐阅读