When I try to run the following code in my program
setTimeout("alert('moo')", 1000);
I get the following error
Error: Object expected
Code: 800A138F
Source: Microsoft JScript runtime error
Why? Am I calling the wrong function? What I want to do is delay the execution of the subsequent function.
This is due to when a function is executed as a parameter to setTimeout , the execution context is different to the execution context of the function! Now this will print out undefined because the this keyword is executed in the context of the setTimeout function and is therefore not defined.
if you use setTimeout the function update() has to completely finish before the next loop of time occurs, thus only 1 instance will ever be running at one time.
Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.
This is because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. Currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected.
It sounds like you're using setTimeout
in a non-browser-based script (Windows Script Host or similar). You can't do that. You can, however, use WScript.Sleep
to suspend your script briefly, with which you can achieve a similar effect. Also, alert
is not a WSH function; you may want WScript.Echo
. More on the WSH reference on MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With