Is there ever a good reason to pass a string to setTimeout?

You can always use global variables by accessing them as properties of the window object, like window.globalVar (though using globals is indeed not a good practice), so no, I don’t think there is ever a good reason to use the deprecated syntax.

It is probably allowed for historical reasons: as Felix Kling mentioned, the original syntax did only allow to pass a string of code:

Introduced with JavaScript 1.0, Netscape 2.0. Passing a Function object reference was introduced with JavaScript 1.2, Netscape 4.0; supported by the MSHTML DOM since version 5.0. [source, my emphasis]

If browsers don’t support the use of a string as first argument to setTimeout and setInterval anymore, there will be lots of code on the internet that doesn’t function anymore.

Leave a Comment