开发者

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??

开发者_C百科Thanks


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


It doesn't sound very robust. But anyway:

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

function doSecondThing() {
...
}


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜