![]() So, looping waiting for some variable to change will never work because no other code can run to change that variable. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. ![]() ![]() Instead, any code that you want to run delays must be inside the setTimeout() callback function (or called from that function). You cannot just pause javascript execution for a predetermined amount of time. It will not wait until after the timeout fires in the stateChange() function. The console.log() statement will run immediately. function wait(ms)īut, if you have code like this: stateChange(-1) Exceptions Throws the rejection reason if the promise or thenable object is rejected. Return value The fulfillment value of the promise or thenable object, or, if the expression is not thenable, the expression's own value. Use clearTimeout(myTimeout) to prevent myGreeting from. Syntax await expression Parameters expression A Promise, a thenable object, or any value to wait for. It's not that hard to use actually, instead of writing this: var x 1 // Place mysterious code that blocks the thread for 100 ms. However, if in some non-production case you really want to hang the main thread for a period of time, this will do it. Wait 5 seconds for the greeting: const myTimeout setTimeout(myGreeting, 5000). 151 Unfortunately, setTimeout () is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI. Joseph Silber has demonstrated that well in his answer. You really shouldn't be doing this, the correct use of timeout is the right tool for the OP's problem and any other occasion where you just want to run something after a period of time.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |