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")}
This is called a function expression. You are assigning an anonymous function to the variable named x
. It works the same as writing:
function x() {
console.log("hello")
}
So you would call the function the same way x()
But why does const myTimeout = setTimeout(myGreeting, 5000);
work without being called like this myTimeout()
? It seems to get called on page load.
Because myTimeout
is not a function. It is an integer (the return value of calling setTimeout
). setTimeout
is being called here with two arguments. The first argument is the function myGreeting
and the second argument is the number 5000
.
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.