Julian Lachniet Julian Lachniet - 5 months ago 34
Javascript Question

Why does setTimeout require code to be enclosed in function?

In JavaScript, the

function requires code to be enclosed in a function.

Examples of invalid timeouts:

  • window.setTimeout(console.log('PING'),3000)

  • function ping(){console.log('PING')};window.setTimeout(ping(),3000)

Example of valid timeouts:

  • window.setTimeout(function(){console.log('PING')},3000)

  • function ping(){console.log('PING')};window.setTimeout(function(){ping()},3000)

Now my question: why? I understand why normal code might need to be enclosed in a function, but why is it ALWAYS necessary to enclose code in


It doesn't always require an anonymous function. You can also pass a function reference as the first argument, for example, let's assume you have a function called log defined. You can validly write:

function log()
    console.log( 'PING' );

window.setTimeout( log, 200 );

Notice that we don't pass the parentheses with the first argument here.

However, you're not able to pass parameters directly to log() in this instance, so it's necessary to wrap the function call inside an anonymous function.