javascript/jquery - 将去抖动添加到按钮

新手上路,请多包涵

我想向按钮添加去抖动,但我想在每次用户单击按钮时执行一些操作,但仅在用户单击按钮后 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));

原文由 george 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 294
2 个回答

您仍然可以像这样使用 $.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);
     });
}());

原文由 Felix Kling 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 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>

原文由 Brandon Boone 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏