Javascript's setInterval() seems to pay no attention to whether or not the code it calls throws exceptions. For instance, this will not terminate the program but call the function over and over again:
setInterval(function() { throw "error" }, 1000);
What is the reason for this behaviour? Is it documented anywhere?
why is setInterval inaccurate? As we know, setTimeout means to run the script after the minimum threshold (MS unit), and setInterval means to continuously execute a specified script with the minimum threshold value period. Note that I use the term minimum threshold here because it is not always accurate.
setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .
This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.
You cannot "wait" for an timeout/interval to finish - trying to do so would not work or block the whole page/browser. Any code that should run after the delay needs to be called from the callback you passed to setInterval when it's "done".
The MDN docs for throw
say, for a thrown object:
If no catch block exists among caller functions, the program will terminate.
This isn't strictly accurate. ECMAScript spec section 10.4
A thrown exception may also exit one or more execution contexts.
This is more accurate.
What is an execution context? Well, there's one for your original program. When you make a function call, a nested context is created while that function is running. A call to eval
will make one. 10.4 covers this.
In general, when an exception is thrown, it will pass up through all of the nested execution contexts until it is caught, or it reaches the outer execution context. If it is not caught within an execution context, that context will be terminated. Thus, if your original program is the outermost execution context, it will terminate on an uncaught exception?
When your handler function is called, due to your setTimeout
interval expiring, it is the outermost execution context. Thus, the uncaught exception terminates it, but it is not nested within your original program. So nothing else gets terminated.
The thread that's handling the timer expires is part of the JS engine, so you're not going to terminate that either. Thus, once per interval, a new execution context is created when your handler function is called and so it repeats.
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