javascript 如何将 debounce fn 实现到 jQuery keyup 事件中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28948383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement debounce fn into jQuery keyup event?
提问by crashwap
A calculation is based on user input, and criteria is to use keyup
rather than change
or blur
.
计算基于用户输入,标准是使用keyup
而不是change
或blur
。
The problem is that the code fires on every keystroke, and I need it to delay and fire only once after a 500ms timeout. My example below obviously doesn't work, fiddle attached.
问题是代码在每次击键时触发,我需要它在 500 毫秒超时后延迟和触发一次。我下面的例子显然不起作用,附上小提琴。
I found David Walsh's dbounce
function, but cannot figure out how to implement it.
我找到了 David Walsh 的dbounce
函数,但不知道如何实现它。
HTML:
HTML:
<input type="text" />
<input type="text" id="n2" class="num" value="17" disabled />
<input type="text" id="n3" class="num" value="32" disabled />
javascript/jQuery:
javascript/jQuery:
$('input').keyup(function(){
var $this=$(this);
setTimeout(function(){
var n1 = $this.val();
var n2 = $('#n2').val();
var n3 = $('#n3').val();
var calc = n1 * n2 * n3;
alert(calc);
},500);
});
//http://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};