我想为一个按钮添加一个debounce,但我希望每次用户点击按钮时执行一些操作,但只有在用户点击按钮后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));
答案 0 :(得分:22)
你仍然可以这样使用$.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);
});
}());
答案 1 :(得分:10)
使用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>
答案 2 :(得分: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
}
答案 3 :(得分:-3)
为什么不使用setTimeOut(function() { process(); }, 5000);