javascript / jquery - 为一个按钮添加去抖动 [英] javascript/jquery - add debounce to a button

查看:520
本文介绍了javascript / jquery - 为一个按钮添加去抖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为一个按钮添加一个debounce,但我希望每次用户点击按钮时执行一些操作,但只有在用户点击按钮后5秒钟后才执行,然后执行SQL更新。通常,节流似乎直接应用于监听器。在这里,我希望每次单击按钮时执行一些操作,然后在合理的等待时间后进行更新。

I want to add a debounce to a button, but i want to perform some actions each time user clicks button, but only after 5 second after user hits button, then perform SQL update. Usually the throttle seems to be applied directly to the listener. Here I want some actions performed each time the button is clicked, and then an update after a reasonable waiting period.

我不知道如何在这种情况下使用该功能...

I am not sure how to use the function in this case...

参考: 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
}



去抖动语法



debounce syntax

$('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 (你可以总是以这种方式去抖你的代码,没有jQuery):

Alternative without $.debounce (you can always debounce your code this way, without 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);
     });
}());

这篇关于javascript / jquery - 为一个按钮添加去抖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆