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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:48:58  来源:igfitidea点击:

How to implement debounce fn into jQuery keyup event?

javascriptjquery

提问by crashwap

A calculation is based on user input, and criteria is to use keyuprather than changeor blur.

计算基于用户输入,标准是使用keyup而不是changeblur

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 dbouncefunction, but cannot figure out how to implement it.

我找到了 David Walsh 的dbounce函数,但不知道如何实现它。

jsFiddle

js小提琴

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

回答by squiroid

Use it like this:-

像这样使用它:-

$('input').keyup(debounce(function(){
        var $this=$(this);
        //alert( $this.val() );
        var n1 = $this.val();
        var n2 = $('#n2').val();
        var n3 = $('#n3').val();
        var calc = n1 * n2 * n3;
        alert(calc);
    },500));

Fiddle

小提琴