javascript 如何设置两个js函数之间的延迟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5787207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set delay between two js functions?
提问by Awan
I have following js code:
我有以下js代码:
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.
在上面的代码中。第一条语句是在磁盘上创建一个 csv 文件。第二条语句正在下载它(使用 iframe 下载文件,因为使用 AJAX 请求时出错)。它正在下载文件,但具有以前的内容。这意味着它会在完成更新该文件之前提示我下载文件。
How can I force my 2ndstatement to not execute before 1st statement finished its work??
如何强制我的第二条语句在第一条语句完成其工作之前不执行?
Thanks
谢谢
回答by neebz
The best way to do something like this in Javascript is to use callback functions.
在 Javascript 中执行此类操作的最佳方法是使用回调函数。
If it is possible to change the reloadTable function such that >
如果可以更改 reloadTable 函数,使得 >
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.
然后在 reloadTable 函数中,在一切完成后调用回调函数。
This is the true beauty of Javascript.
这就是 Javascript 的真正魅力。
Otherwise you can also use setTimeout() if you have an idea how much time the reloadTable takes.
否则,如果您知道 reloadTable 需要多少时间,也可以使用 setTimeout()。
e.g. if it is to take 1 second. to complete, you can >
例如,如果要花 1 秒钟。要完成,您可以 >
clientData.reloadTable( "CreateCSV", "create/file" );
var func = function () { $("#downloadFrame").attr("src","/download/download");}
setTimeout(func, 1000);
回答by helios
It doesn't sound very robust. But anyway:
听起来不是很健壮。但无论如何:
function start() {
doFirstThing();
setTimeout('doSecondThing();', 1000); // execute the secondthing in 1000 ms
}
function doSecondThing() {
...
}
回答by Headshota
clientData.reloadTable( "CreateCSV", "/create/file" );
if it's an ajax call. call your download function from it's callback.
如果是ajax调用。从它的回调中调用你的下载函数。