Debounce function in Jquery?

slikk picture slikk · Aug 9, 2017 · Viewed 7.5k times · Source

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??

Answer

Dr4v picture Dr4v · Mar 26, 2019

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);
});