Where is the function called here?

I was looking into setTimeout and came across this simple example. But I don’t understand where the function is called, since it’s only assigned to the myTimeout variable, and also how come it’s using a function that hasn’t been declared as a callback function? Since myGreeting is declared after myTimeout.

It’s called here:

setTimeout(myGreeting, 5000)

This says to call the function myGreeting in 5 seconds. setTimeout returns an ID for the timer that can be used to cancel the timeout before it executes the function.

The function myGreeting is declared right below. It’s using the traditional method of declaring a function and thus it can be accessed in code above it (this is referred to as “hoisting”).

I thought it was just assigning it to a variable called myTimeout, I was expecting to have to call it using myTimeout()
How come this doesn’t work without calling x() then?

const x = function() {console.log("hello")}

But why does const myTimeout = setTimeout(myGreeting, 5000); work without being called like this myTimeout()? It seems to get called on page load.

What kind of return value can calling setTimeout have? I tried console logging the myTimeout variable and it always returns 1.

It can be any positive number. It’s up to the JS runtime to decide what number it wants to use. You don’t really need to worry about what that actual number is. But if you might need to cancel the timeout before it is executed then you can store the return value in a variable and pass it into clearTimeout to cancel it. Otherwise, if you’ll never need to cancel it then you can basically just forget about the return value.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.