javascript / jquery – 为一个按钮添加去抖动
我想为一个按钮添加一个debounce,但我希望每次用户点击按钮时执行一些操作,但只有在用户点击按钮后5秒钟后才执行,然后执行SQL更新。 通常,节流似乎直接应用于监听器。 在这里,我希望每次单击按钮时执行一些操作,然后在合理的等待时间之后进行更新。
我不确定如何在这种情况下使用该function……
参考: 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));
您仍然可以像这样使用$.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
替代$.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); }); }());
使用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
Click me fast! Native Click me fast! jQuery + Underscore
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 }
为什么不使用setTimeOut(function() { process(); }, 5000);