hyptos
hyptos

Reputation: 160

how could I pass closure problems in order to increment a global var

I have a simple goal, I would like to increment a variable but I'm facing the closure problem. I've read why this s happening here How do JavaScript closures work?

But I can't find the solution to my problem :/

let's assume this part of code I took from the link.

function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); //incrementation
}
num++;
return sayAlert;
}

I would like to increment num within the function and to keep the changes to num.

How could I do that ?

Here is the JsFiddle where I have my problem, I can't figure out how to increment my totalSize and keep it.

http://jsfiddle.net/knLbv/2/

I don't want a local variable that ends up with closure.

Upvotes: 1

Views: 95

Answers (3)

jbl
jbl

Reputation: 15413

From your fiddle, I guess the problem is a mix of closure (totalSize should be outside of the loop) and query.exec being asynchronous (this one can be verified with some console.log).

What you seem to need is some kind of control flow, something like async.reduce

Upvotes: 2

Instance Noodle
Instance Noodle

Reputation: 227

function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num++); //incrementation
}
return sayAlert;
}

var inscrese = say667();

so if you want to increase by one just call increase();

Upvotes: 0

pts
pts

Reputation: 87311

If all other solutions fail, then make num an array: var num = [666], then increment it's first element: num[0]++.

Upvotes: -1

Related Questions