Debounce function in Jquery?

2020-05-06 20:54发布

Been looking for a debounce function or way to debounce in Jquery. The build up of animations can get super annoying. Heres the code:

function fade() {
    $('.media').hide();
    $('.media').fadeIn(2000);
}
var debounce = false;
function colorChange() {

    if (debounce) return;
    debounce = true;
    $('.centered').mouseenter(function() {
    $('.centered').fadeTo('fast', .25);
    });
    $('.centered').mouseleave(function() {
    $('.centered').fadeTo('fast', 1);
});
}

 function colorChange2() {
    $('.centered2').mouseenter(function() {
    $('.centered2').fadeTo('fast', .25);
});
$('.centered2').mouseleave(function() {
    $('.centered2').fadeTo('fast', 1);
});
}

function colorChange3() {
$('.centered3').mouseenter(function() {
    $('.centered3').fadeTo('fast', .25);
});
$('.centered3').mouseleave(function() {
    $('.centered3').fadeTo('fast', 1);
});
}

function closerFade() {
    $('.closer').hide();
    $('.closer').fadeIn(2000);
}

I wrapped those all in $(document).ready(function() {

Is there way to debounce??

2条回答
Explosion°爆炸
2楼-- · 2020-05-06 21:13

I don´t like the idea to include a library just for a debounce function. You can just do:

var debounce = null;
$('#input').on('keyup', function(e){
   clearTimeout(debounce );
   debounce = setTimeout(function(){
      $.ajax({url: 'someurl.jsp', data: {query: q}, type: 'GET'})
   }, 100);
});
查看更多
迷人小祖宗
3楼-- · 2020-05-06 21:16

I would just include underscore.js in my project and use the debounce function that it contains. It works great. I've used it in multiple projects.

http://underscorejs.org/#debounce

debounce_.debounce(function, wait, [immediate]) Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

At the end of the wait interval, the function will be called with the arguments that were passed most recently to the debounced function.

Pass true for the immediate argument to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. Useful in circumstances like preventing accidental double-clicks on a "submit" button from firing a second time.

var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
查看更多
登录 后发表回答