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

ネイティブ/バニラ 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 に答える