getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

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
                _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();

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

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

Added by Ciprian on Thursday, January 11, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy