Using javascript how to break the while loop after a set time? [duplicate]

守給你的承諾、 提交于 2019-12-11 00:08:53

问题


I have a while loop which looks like this:

while(s1 != "#EANF#")
{
iimPlay("CODE:REFRESH");
iimPlay("CODE:TAG POS=1 TYPE=* ATTR=TXT:Contacted:* EXTRACT=TXT")
var s1 = iimGetLastExtract();
}

it will refresh the web page until it finds what it wants. However sometimes it becomes an infinite loop and I want to simply set a timer so that it would break the while loop and carry on. I tried looking at settimeout but couldn't figure out how to do it. I want this while loop to just give up refreshing the web page if it doesn't find what it wants after lets say 3 minutes.


回答1:


EDIT: This may not be the correct answer...please see comments


You can use a flag that is flipped after 3 minutes in your while loop condition:

var keepGoing = true;
setTimeout(function() {
    // this will be executed in 3 minutes
    // causing the following while loop to exit
    keepGoing = false;
}, 180000); // 3 minutes in milliseconds

while(s1 != "#EANF#" && keepGoing === true)
{
iimPlay("CODE:REFRESH");
iimPlay("CODE:TAG POS=1 TYPE=* ATTR=TXT:Contacted:* EXTRACT=TXT")
var s1 = iimGetLastExtract();
}



回答2:


About your question you may define a flag variable and check it in while loop and change its value in timer.

Like :

your while loop:

while(mflag==0){
    //codes
}

Your timer function

Function mtimer(){
    mflag=1;
}

And somewhere before while loop:

var mflag=0;
var mt= setTimeout(mtimer,3*60*1000);

But what I want to say is that I think you have wrong approach in refreshing webpage in a while loop. Maybe you should use Ajax or something. And I might be able to help if you give more information about whole thing you are about to do.



来源:https://stackoverflow.com/questions/34069086/using-javascript-how-to-break-the-while-loop-after-a-set-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!