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. What code should wait 5 seconds if you mean the HTML code to display after 5 seconds, set its CSS display to none and after 5 seconds set it to the previous value (an empty string. The console.log() statement will run immediately. function wait(ms)īut, if you have code like this: stateChange(-1) However, if in some non-production case you really want to hang the main thread for a period of time, this will do it. Joseph Silber has demonstrated that well in his answer. This function enables you to build more dynamic and interactive webpages. This article demonstrated how to use the setTimeout () method in JavaScript to wait for 5 seconds using real-world scenarios. 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. an async function), you can use the 'await' keyword to wait for a Promise to resolve before continuing to the next line of the function. JavaScript’s setTimeout () function is a helpful tool that lets you delay the execution of certain code for a predetermined amount of time.
0 Comments
Leave a Reply. |