Execution Context, binding, & anonymous functions in setTimeout() !

When/why do we use anonymous functions with setTimeout()?

Let’s say I have a function that congratulates you on a job well done.

var name = "Window";
var person = {
name: "Paul"
cheer: function () {
alert(this.name + ", well done!");
}
};

setTimeout(person.cheer, 1000);

What will happen when setTimeout is called?

The function person.cheer, will execute after 1000 milliseconds (1 second).

In what context?

In other words, when I call this method, what is its execution context? “this”, is the object that a function points to when executing. Since person.cheer method isn’t explicitly bound to an object within setTimeout, “this” will defer to the Window/Global object.

When we get to the alert() statement in setTimeout, will invoke window.name will be used, which in this case is (a bit confusingly) called “Window”.

Window, well done!” will be alerted after 1000 milliseconds.

If we want to bind our cheer method to a specific object, we can use .bind() !

var name = "Window";
var person = {
name: "Paul",
cheer: function () {
alert(this.name + ", well done!");
}
};
var Jasmine = { name: 'Jasmine'; }
var cheer = person.cheer.bind(Jasmine);

setTimeout(function() {
    window.cheer();
}, 1000);

This time, there is a cheer a variable available in the global scope. Notice the use of bind() to attach the cheer method to Jasmine on execution. Now when you call window.cheer, you can expect the result to be “Jasmine, well done!” because we’ve intentionally bound the cheer method to Jasmine.

If window.cheer() were not wrapped in a function in setTimeout, it would run immediately, not after 1000 milliseconds:

setTimeout(window.cheer()}, 1000); // This will run immediately!

This code passes in the result of a function invocation, not the function itself. We need to wrap window.cheer() within another function in order for setTimeout to work properly.

setTimeout(function(){
window.cheer();
} //This will work :]
}, 1000);

For an excellent explanation of ‘this’, execution contexts, and binding checkout this Udemy course!