Use ‘this’ Keyword with setTimeout()

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 you need to send variables.

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
      "Hello world");
            } , 2000);

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

        // Once all methods have been defined, start the timer

    // Once the application has been defined, start it

// Usage

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Leave a Reply

My Battle Tested Recommendations


Disclaimer: These recommendations contain affiliate links.