javascriptjquerysettimeoutjquery-eventsdelayed-execution

Delay JavaScript's function execution


I have a JQuery's .each loop that calls a function with a parameter per iteration, is there a way to delay this function call? I have tried setTimeout as in the following but this does not work as the function gets executed immediately.

$.each(myArray, function (j, dataitem)
{
     setTimeout(function () { showDetails(dataitem) }, 300);
});

function showDetails(dataitem)
{
...
}

Array size is roughly 20, What I'm trying to do is to distribute function calls over a certain time frame instead of immediately, any idea how to achieve this? I'm prepared to rewrite and restructure how functions get called to get this done, any help would be appreciated.


Solution

  • You could use the index of the array to calculate the interval dynamically:

    $.each(myArray, function (j, dataitem) {
        window.setTimeout(function () { 
            showDetails(dataitem) 
        }, (j + 1) * 300);
    });