Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 920
Awan Avatar asked Dec 07 '25 10:12

Awan


1 Answers

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);
like image 196
neebz Avatar answered Dec 10 '25 00:12

neebz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!