I use this small function for the same purpose, executing a function after the user has stopped typing for a specified amount of time or in events that fire at a high rate, like resize
:
(我将这个小功能用于相同的目的,即在用户停止输入指定的时间后或在触发率很高的事件中执行一个功能,例如resize
:)
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));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="input">Try it: <input id="input" type="text" placeholder="Type something here..."/> </label>
How it works:(怎么运行的:)
The delay
function will return a wrapped function that internally handles an individual timer, in each execution the timer is restarted with the time delay provided, if multiple executions occur before this time passes, the timer will just reset and start again.
(delay
函数将返回一个包装的函数,该函数在内部处理单个计时器,在每次执行中,计时器都将按提供的时间延迟重新启动,如果在这段时间过去之前发生了多次执行,则计时器将重置并重新启动。)
When the timer finally ends, the callback function is executed, passing the original context and arguments (in this example, the jQuery's event object, and the DOM element as this
).
(当计时器最终结束时,将执行回调函数,并传递原始上下文和参数(在此示例中,是jQuery的事件对象,而DOM元素是this
)。)
UPDATE 2019-05-16(更新2019-05-16)
I have re-implemented the function using ES5 and ES6 features for modern environments:
(我已针对现代环境使用ES5和ES6功能重新实现了该功能:)
function delay(fn, ms) {
let timer = 0
return function(...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms || 0)
}
}
The implementation is covered with a set of tests .
(该实现包含一组测试 。)
For something more sophisticated, give a look to the jQuery Typewatch plugin.
(对于更复杂的内容,请看一下jQuery Typewatch插件。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…