Use ‘this’ Keyword with setTimeout()

on in Methods, Events and Scopes
Last modified on

setTimeout() is a great help to many JavaScript developers. For example, you may wish to add a delay to allow some animation to complete. This method is very easy to use.

The problem arises when you need to use it within a specific scope, for example when the function or method you are trying to call needs to be combined with the this keyword or when you need to send variables.

What we need to do is to get a reference to the initial scope as _this. _this is available to the code here because the functions that enclose it have access to the variables in the scope within which they have been enclosed. This is called “closure”. this is also available to the code here but will now refer to the scope local to this function, not the scope referenced by _this.

function createExample() {
    // Define a simple application, creating scope
    application = function () {
        // Get a reference to the scope
        _this = this;

        // Create a method to start the timer
        startTimer = function () {
            setTimeout(function () {
                // _this is available to the code here because the functions that
                // enclose it have access to the variables in the scope within which
                // they have been enclosed. This is called "closure".

                // this is also available to the code here but will now refer to the
                // scope local to this function, not the scope referenced by _this.

                // Arguments can be supplied just as you always would
                _this.show('Hello world');
            } , 2000);
        }

        // Create a method to run when the timer has completed,
        // complete with expected arguments
        show = function (textToShow) {
            console.log(textToShow);
        }

        // Once all methods have been defined, start the timer
        this.startTimer();
    }

    // Once the application has been defined, start it
    application();
}

// Usage
createExample();

Related posts