13

我想为按钮添加去抖动功能,但我想在每次用户单击按钮时执行一些操作,但仅在用户单击按钮后 5 秒后执行 SQL 更新。通常油门似乎直接应用于侦听器。在这里,我希望每次单击按钮时执行一些操作,然后在合理的等待期后进行更新。

我不确定在这种情况下如何使用该功能...

参考:http ://code.google.com/p/jquery-debounce/

$('#myButton').click(function() {
    // do a date calculation
    // show user changes to screen
    // wait until user has has stopped clicking the 
             // button for 5 seconds, then update file with "process" function.

});

function process(){
    // update database table
}

去抖动语法

$('input').bind('keyup blur', $.debounce(process, 5000));
4

4 回答 4

23

你仍然可以$.debounce像这样使用:

// create new scope
(function() {
     // create debounced function
     var dprocess = $.debounce(process, 5000);

     // bind event handler
     $('#myButton').click(function() {
         // do a date calculation
         // show user changes to screen
         // call the function
         dprocess();
     });
}());

没有的替代方案$.debounce(你总是可以用这种方式去抖动你的代码,没有 jQuery):

// create new scope
(function() {
     var timer;

     // bind event handler
     $('#myButton').click(function() {
         if(timer) {
             clearTimeout(timer);
         }
         // do a date calculation
         // show user changes to screen
         // call the function
         timer = setTimeout(process, 5000);
     });
}());
于 2011-11-08T19:34:14.547 回答
14

使用 native/vanilla JS 和 jquery/underscore.js 去抖动。

例子

JS

//Native/Vanilla JS
document.getElementById('dvClickMe').onclick = debounce(function(){
    alert('clicked - native debounce'); 
}, 250);


function debounce(fun, mil){
    var timer; 
    return function(){
        clearTimeout(timer); 
        timer = setTimeout(function(){
            fun(); 
        }, mil); 
    };
}

//jQuery/Underscore.js
$('#dvClickMe2').click(_.debounce(function(){
    alert('clicked - framework debounce'); 
}, 250)); 

HTML

<div id='dvClickMe'>Click me fast! Native</div>
<div id='dvClickMe2'>Click me fast! jQuery + Underscore</div>
于 2013-03-13T03:47:05.403 回答
4
 var timer;
 $('#myButton').click(function() {
     //Called every time #myButton is clicked         
     if(timer) clearTimeout(timer);
     timer = setTimeout(process, 5000);
 });

function process(){
  //Called 5000ms after #myButton was last clicked 
}
于 2012-12-05T14:34:49.290 回答
-4

为什么不直接使用setTimeOut(function() { process(); }, 5000);

于 2011-11-08T19:36:47.250 回答