ILikeThePoopSmith
ILikeThePoopSmith

Reputation: 121

Why does setting a variable equal to setTimeout function immediately run it?

I have the following code

  setTimeout(function() {
    alert('Hello, Mr. Universe!');
  }, 2000)

This runs immediately, and outputs the alert after 2 seconds (at least) depending on the stack. But I'm wondering why the following also behaves this way.

  let myGreeting = setTimeout(function() {
    alert('Hello, Mr. Universe!');
  }, 2000)

Isn't this just a function expression? Why does it run even without an invocation, i.e., myGreeting()?

Upvotes: 1

Views: 650

Answers (4)

danh
danh

Reputation: 62686

To initiate the timeout by making a function call, do the setTimeout in body of the function, rather than assigning it...

// not const myGreeting = setTimeout, but...
const myGreeting = () => {
  return setTimeout(() => {
    alert('Hello, Mr. Universe!');
  }, 2000);
}

// call it
const timeoutId = myGreeting() // after 2 seconds, 'Hello..."

Upvotes: 2

Ernesto
Ernesto

Reputation: 4252

??? Oki let’s take whatever setTimeout has inside setTimeout() you is calling it that’s why it runs

Upvotes: -1

JayC
JayC

Reputation: 7141

It seems you are confused as to the semantics of let. The right hand expression of the equal sign here is still getting evaluated at the time of assignment. You are not "setting myGreeting to some expression. You are setting myGreeting to the result of evaluating some expression.

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89224

setTimeout returns an id to use with clearTimeout. In your first example, you are just ignoring the return value, so the result should not differ.

Upvotes: 1

Related Questions