Search code examples
jqueryfunctioncall

Call several times a function, already running


I use the dropzone library to upload files and once a file is uploaded, I call a function that retrieves the list of files on the server. The problem is that when I import small files, the function that retrieves the files is executed "at the same time", more precisely: a call to this function is already running.

What I would like is to put a flag to restrict access to this function, only when it is finished.

//Listener on add file
dropzone.on("complete", function (file)
    ajaxListFiles();
});

Thanks !


Solution

  • You could just set a running flag when the function starts and unset it when it ends. Then just check this flag before executing the function again:

    let running = false;
    
    dropzone.on("complete", function (file)
        if (!running) {
            ajaxListFiles();
        }
    });
    
    function ajaxListFiles() {
        running = true; // at the very beginning of this function
    
        // ... your code
    
        running = false; // when it ends, so probably in some callback, not necessary at the end of this function
    }