4

I'm trying to get a global object to modify one of its own variables in a callback function initialised by one of its own methods. The callback appears to work, but the variable doesn't seem to have been modified when testing the global variable.

Why is the global object not being modified? Are the changes to the global object kept in some sort of staging area pending completion of the callback function?

let obj;

function test_object_flag() {

    // 5 - check whether the "timer_finished" flag has been set
    console.log("is the timer finished? " + obj.timer_finished);    // should return "true"???

}

class TestClass {

    constructor() {
        this.timer_finished = false;
    }

    start_timer(ptr_callback_function) {

        // 3 - set up a callback for the timer
        setTimeout(function() {

            // 4 - once the timer is done, set a "timer_finished" flag, and call the callback
            this.timer_finished = true;
            ptr_callback_function();

        }, 1000);

    }

}

$( document ).ready(function() {

    // 1 - make a new onbject of type TestClass
    obj = new TestClass();

    // 2 - start the timer 
    obj.start_timer(test_object_flag);

});
1

1 Answer 1

4

The problem is that setTimeout creates it's own this. Solution may looks like:

start_timer(ptr_callback_function) {
    // savig this that your need
    const self = this;

    setTimeout(function() {
        // use needed context
        self.timer_finished = true;
        ptr_callback_function();
    }, 1000);
}

Another option is to use arrow functions:

start_timer(ptr_callback_function) {
    setTimeout(() => {
        this.timer_finished = true;
        ptr_callback_function();
    }, 1000);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This would be a good use-case for an arrow function as well. No need to set self variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.