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?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments