javascript/jquery - add debounce to a button

2019-01-17 08:49发布

I want to add a debounce to a button, but i want to perform some actions each time user clicks button, but only after 5 second after user hits button, then perform SQL update. Usually the throttle seems to be applied directly to the listener. Here I want some actions performed each time the button is clicked, and then an update after a reasonable waiting period.

I am not sure how to use the function in this case...

reference: 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
}

debounce syntax

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

4条回答
贼婆χ
2楼-- · 2019-01-17 09:01

You could still use $.debounce like so:

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

Alternative without $.debounce (you can always debounce your code this way, without 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);
     });
}());
查看更多
爷的心禁止访问
3楼-- · 2019-01-17 09:03

Debounce using native/vanilla JS and jquery/underscore.js.

Example

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>
查看更多
forever°为你锁心
4楼-- · 2019-01-17 09:12

Why not just use setTimeOut(function() { process(); }, 5000);

查看更多
Animai°情兽
5楼-- · 2019-01-17 09:25
 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 
}
查看更多
登录 后发表回答