user1283776
user1283776

Reputation: 21764

Is the value of a variable in a closure that is called twice the same in both closures?

Say that this function is called twice, completely independently. Hence timeout callbacks are created for two functions fn() and both functions have a variable called called in their closure.

Will this be the same variable or two completely independent variables? Why?

function createFunctionWithTimeout(callback, opt_timeout) {
    var called = false;
    function fn() {
        if (!called) {
            called = true;
            callback();
        }
    }
    setTimeout(fn, opt_timeout || 5000);
    return fn;
}

Upvotes: 0

Views: 188

Answers (3)

nitte93
nitte93

Reputation: 1840

Every time you call a new function, it creates its own independent scope and the object inside this scope is only relevant to this particular scope, in otherword, your called variable is two completely independent variables.

Upvotes: 0

adam-beck
adam-beck

Reputation: 6009

A function closes over a variable declared with var. called in your scenario will be two completely independent variables because when the function createFunctionWithTimeout is called twice, each call "creates" a new variable.

If you call the returned function (fn) it will have access to the called variable because it also closes over it (nested functions). In this case, called is not independent. It belongs to the closure created by the call to createFunctionWithTimetout

Upvotes: 2

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

All declared inside createFunctionWithTimeout will be created on each call.

This called function scope and made like this by design.

Read this article and also look about scope in JS.

http://www.w3schools.com/js/js_scope.asp

BTW. To make variable called be same for each call you need to make it global. Like put it outside of function. In that case they will use same variable.

Hope this helps.

Upvotes: 0

Related Questions