Does anybody know how to create a loop that will just kill time until a flag is set. Maybe something like: var flag =false; while ( flag == false ){ //kill time then check if flag is true yet //If flag is still false kill some more time } Thanks, Mike
While what you are coding is likely easiest coded as: do {} while (!flag); There is a MASSIVE problem with doing that in Javascript. Scripting is NOT multithreaded or multitasking, EVENT event driven code. When events fire they are put onto their own 'stack' -- the code called by an event will NOT execute until no other scripts are running. As such, unless you have code inside that while statement to change the flag, there is NO way for ANY other code -- be it by event, timeout, etc -- will run... so if no code to modify 'flag' can can actually run inside that loop, there is no way for that loop to end. You are thinking linear execution on code that shouldn't be -- in an engine that is inherently linear. Leaving scripting "running" is just sloppy and won't work -- Trying to do that will even make browsers like FF and Opera throw a warning and halt executing scripts on the page after a certain amount of time. What is it exactly you are trying to do? If you have some other code that modifies flag, why isn't it calling the code you want to run when 'flag' changes from that event?
function loopFoo() { if (!flag) { setTimeout(loopFoo, 1000); // additional code } } setTimeout(loopFoo, 1000);
I'm trying to get the hang of async coding, but here is the basic scenario. I am executing the code inside of function "A". At some point within function "A" I want to call another function "B" which will fade an element to 0. But, I don't want to continue processing function "A" until function "B" is done fading the element. If I use a callback function in function "B" it doesn't help me because as soon as "B" kicks off the fade operation the javascipt engine goes back to "A" to pick up where it left off and continue processing the code in "A". The behavior I want is for the js engine to stay inside "B" until the fade is complete, and then come back to "A" to run the rest of the "A" code. I'm pretty new to js, so I'm sure there is a better way to achieve my objective. I welcome any advice you might have. Thanks, Mike
For that, there is no need to freeze the browser. There must be a part in that fade code that says when the fading is finished. I would execute the callback to A there. If not that, then set an interval to check the style of your faded element every 200ms or so (or whatever). Once you can determine that the fading is finished, you can execute the callback.