-2

I am trying to understand why this snippet of code logs the string 'Bob says hi' immediately and does not wait the expected time.

var name = "Window";
var alice = {
  name: "Alice",
  sayHi: function() {
    console.log(this.name + " says hi");
  }
};
var bob = { name: "Bob" };

setTimeout(alice.sayHi.call(bob), 1000);

What is making the setTimeout function not execute after the wait argument?

The question has been marked as duplicate. Yet I don't see it being identical. This question is using call but the one referenced is not.

jkdev
  • 11,360
  • 15
  • 54
  • 77
davefogo
  • 93
  • 1
  • 9
  • You're calling the method immediately and attempting to schedule the execution of the *result* of the function call. What did you think `call(...)` did? –  Jul 05 '18 at 18:59
  • `setTimeout` wants a function reference, `call` calls the function immediately. – zero298 Jul 05 '18 at 18:59

1 Answers1

2

setTimeout takes as the first parameter a function, alice.sayHi.call(bob) is not a function, it's undefined (it is the returned value of the function, not the actual function).

So you need to specify a callback instead, wrap your function inside another one like so:

var name = "Window";
var alice = {
  name: "Alice",
  sayHi: function() {
    console.log(this.name + " says hi");
  }
};
var bob = { name: "Bob" };

setTimeout(() => {
  alice.sayHi.call(bob)
}, 1000);

In the above code (using the arrow function syntax) I'm giving setTimeout the function () => { alice.sayHi.call(bob) }. After 1 second, the function will be executed i.e alice.sayHi.call(bob) will be called.

Ivan
  • 34,531
  • 8
  • 55
  • 100