[英]Wait for few seconds before next action - Javascript
As commented in the code , I need a wait before checking the else if
after writeFile(lFileData);
正如在代码中所评论的那样,我需要在检查
else if
之前等待, else if
在writeFile(lFileData);
之后writeFile(lFileData);
. 。 How to achieve this?
怎么做到这一点?
for(var i=0;i<mLocalStorageCount;i++)
{
if(i <= 1)
{
writeFile(lFileData); //This action takes a lot of time with its call backs. I need a wait here.
}
else if(i > 1 && i <=3)
{
someOtherfun()
}
if(i <= 1){
writeFile(lFileData);
doAdelay();
};
and: 和:
function doAdelay(){
setTimeout(function(){return true;},30000);
};
Hope this helps 希望这可以帮助
您可以在elseif函数中使用set interval
setTimeout(function,3000);
So that means the writeFile function is asynchronous? 那么这意味着writeFile函数是异步的吗?
I would create a callback function in the writeFile function itself and then do the someOtherfun(). 我会在writeFile函数本身创建一个回调函数,然后执行someOtherfun()。
Edit : Due to you can not really do the rest of the iteration in the callback function (which you just said) you can do something like this: 编辑 :由于你无法真正完成回调函数中的其余迭代(你刚才说过),你可以这样做:
function writeFile () {
... here goes your function ...
if ( finished ) {
window.finished = true;
}
}
for (yourForCondition) {
if () {
window.finished = false;
writeFile();
while (!window.finished) {}
}
if () {
someOtherFun();
}
}
It's a bit dirty, but it should work. 它有点脏,但它应该工作。 It would loop until writeFile() says he is done.
它会循环,直到writeFile()说他完成了。
Edit2 : Will probably not work since "while (!window.finished) {} is a busy-wait loop that will peg one core to 100% and probably make the browser ask the user if the script should be killed. – Frédéric Hamidi " Edit2 :可能不会起作用,因为“while(!window.finished){}是一个繁忙等待循环,它会将一个核心固定到100%,并可能让浏览器询问用户是否应该杀死该脚本。 - FrédéricHamidi”
You may want to rewrite the code to have the portion you want to run on a delay in its own function. 您可能希望重写代码以使您想要在其自己的函数中延迟运行的部分。 From there call that function by calling performFunctionXAfterDelay() :
从那里通过调用performFunctionXAfterDelay()来调用该函数:
function performFunctionXAfterDelay() {
// 1000 ms delay
window.setTimeout(functionX,1000)
}
function functionX() {
// YOUR TIME DELAYED CODE
}
var t = setInterval("javascript expression", milliseconds);
clearInterval(t);
u can use setInterval
你可以使用
setInterval
hi i think there is no need of wait before execution of "else if(i > 1 && i <=3)" code. 嗨,我认为在执行“else if(i> 1 && i <= 3)”代码之前无需等待。 because if "if(i <= 1)" condition is true and " writeFile(lFileData); " gets executed, control will no be given for "else" part and " someOtherfun()" will not get executed.
因为如果“if(i <= 1)”条件为真并且“writeFile(lFileData);”被执行,则不会为“else”部分提供控制,并且“someOtherfun()”将不会被执行。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.