仅在特定时间段后输入元素火灾变化事件

时间:2017-03-02 11:35:43

标签: jquery

我想在特定时间段后只进行一次输入更改。

在下面的代码中假设我输入3个字符,它在1500毫秒后三次警告。

我只想提醒一次。

这是我的js代码。

jQuery("#width").on('input',function(){
setTimeout(function(){
           alert('hello');
     },1500)

});

JSFIDDEL

1 个答案:

答案 0 :(得分:4)

你需要去抖动功能。要么使用lodash _.debounce,要么写自己的简单。然后像这样使用它:

jQuery("#width").on('input', debounce(function() {
  alert('hello')
}, 1500))

简单的去抖功能可能如下所示:

function debounce(callback, delay) {
  var timeout
  return function() {
    var args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(function() {
      callback.apply(this, args)
    }.bind(this), delay)
  }
}

这是一个演示:

jQuery("#width").on('input', debounce(function() {
  alert('hello');
}, 1500));

function debounce(callback, delay) {
  var timeout
  return function() {
    var args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(function() {
      callback.apply(this, args)
    }.bind(this), delay)
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="width" />

相关问题