Search code examples
javascriptjquerydelay

How to set delay between two js functions?


I have following js code:

clientData.reloadTable( "CreateCSV", "/create/file" );
$("#downloadFrame").attr("src","/download/download");

In above code. first statement is creating an csv file on disk. And 2nd statement is downloading it(Using iframe to download file because of error when using AJAX request ). It is downloading file but with previous content. It means that it prompts me to download file before it finish updating that file.

How can I force my 2nd statement to not execute before 1st statement finished its work??

Thanks


Solution

  • The best way to do something like this in Javascript is to use callback functions.

    If it is possible to change the reloadTable function such that >

    var callback = function () { $("#downloadFrame").attr("src", "/download/download") }
    
    clientData.reloadTable("CreateCSV", "create/file", callback);
    

    and then inside the reloadTable function, call the callback function once everything is done.

    This is the true beauty of Javascript.


    Otherwise you can also use setTimeout() if you have an idea how much time the reloadTable takes.

    e.g. if it is to take 1 second. to complete, you can >

    clientData.reloadTable( "CreateCSV", "create/file" );
    var func = function () { $("#downloadFrame").attr("src","/download/download");}
    setTimeout(func, 1000);