geo*_*rge 10 javascript jquery throttling
我想为一个按钮添加一个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
}
Run Code Online (Sandbox Code Playgroud)
$('input').bind('keyup blur', $.debounce(process, 5000));
Run Code Online (Sandbox Code Playgroud)
Fel*_*ing 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();
});
}());
Run Code Online (Sandbox Code Playgroud)
没有替代方案$.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);
});
}());
Run Code Online (Sandbox Code Playgroud)
Bra*_*one 11
使用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));
Run Code Online (Sandbox Code Playgroud)
HTML
<div id='dvClickMe'>Click me fast! Native</div>
<div id='dvClickMe2'>Click me fast! jQuery + Underscore</div>
Run Code Online (Sandbox Code Playgroud)