javascript – How to avoid function calls


I have a call to a function on my systems and it always worked. It is a function to show/hide a loading image for the user. The problem is that sometimes I have to call this function in a user action of a select field, for example, and if the user changes it 10 times in a row, this select field will make 10 calls, which is okay, but it is bad for the user to still show the image because it is loading and disappearing 10 times.

Here's an example to better understand what I'm saying.

In this case it's not any action that takes time to execute, but because I have many ajax calls that can take a little longer, hence the need for me to display it to the loading user.

My code:

$(document).ready(function() {  
     $("select[name=meuSelect]").change(function(event) {

         var valor = $(this).val();


function ajaxLoadAni(inOut) {
    'use strict';

    if (inOut === 'In') {
      $('#ajaxLoadAni').fadeIn('slow'); //EXIBE A IMAGEM DE CARRREGANDO
    } else {
        $('#ajaxLoadAni').fadeOut('slow'); //ESCONDE A IMAGEM DE CARRREGANDO

Example working in JSFiddle


You can solve this easily by stopping the animation using .stop() before giving .fadeOut() and it might be even better if you also give a .stop() to .fadeIn() too as I did some tests and if you change a lot you quickly notice that the animation has repeated itself once, so:

You were using fadeIn() and fadeOut() without stopping:

$('#ajaxLoadAni').fadeIn('slow'); //EXIBE A IMAGEM DE CARRREGANDO
$('#ajaxLoadAni').fadeOut('slow'); //ESCONDE A IMAGEM DE CARRREGANDO

Adding a stop would look like this:

$('#ajaxLoadAni').stop(true,true).fadeIn('slow'); //EXIBE A IMAGEM DE CARRREGANDO    
$('#ajaxLoadAni').stop(true,true).fadeOut('slow'); //ESCONDE A IMAGEM DE CARRREGANDO

This way you will stop the previous animation before exiting, so you don't have to show/hide several times for the user.

Important detail about the stop() function:

The parameters of the .stop() function serve to clear the animation queue and also end them, which would be:


[clearQueue] – If true , indicates that the animation must be removed from the queue.(default false ). [jumpToEnd] – If true , indicates that the animation must be completed immediately.(default false ).

Example working in JSFiddle


Scroll to Top