[英]How to implement debounce fn into jQuery keyup event?
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.问题是代码在每次击键时都会触发,我需要它在 500 毫秒超时后延迟和触发一次。 My example below obviously doesn't work, fiddle attached.
我下面的例子显然不起作用,附上小提琴。
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);
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.