Awan
Awan

Reputation: 18560

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

Upvotes: 2

Views: 14246

Answers (3)

neeebzz
neeebzz

Reputation: 11538

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);

Upvotes: 7

Headshota
Headshota

Reputation: 21449

clientData.reloadTable( "CreateCSV", "/create/file" );

if it's an ajax call. call your download function from it's callback.

Upvotes: 2

helios
helios

Reputation: 13841

It doesn't sound very robust. But anyway:

function start() {
  doFirstThing();
  setTimeout('doSecondThing();', 1000); // execute the secondthing in 1000 ms
}

function doSecondThing() {
...
}

Upvotes: 5

Related Questions