![]() 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. Asynchronous actions in Javascript can usually call upon one of these two functions. 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. How to wait 5 seconds in JavaScript Tim Mousk 9 subscribers 1 Dislike Share 4 views In this video, I explain how to wait 5 seconds in JavaScript. The console.log() statement will run immediately. While JavaScript does not have the sleep () or wait () function, it is not difficult to create one using the setTimeout () function. JavaScript does not have a native sleep function, but thanks to the introduction of promises (and async/await in ES2018) we can implement such. Java has Thread.sleep(2000), Python has time.sleep(2), Go has time.Sleep(2 time.Second). function wait(ms)īut, if you have code like this: stateChange(-1) In a programming language like C or PHP, you’d call sleep(2) to make the program halt for 2 seconds. Just put the code you want to delay in the callback. ![]() However, if in some non-production case you really want to hang the main thread for a period of time, this will do it. One way to delay execution of a function in NodeJS is to use the seTimeout () function. 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. But otherwise, none of these are good solutions. ![]()
0 Comments
Leave a Reply. |