Local variables are overwritten in functions, executed several times in a loop

Hey, I have a little problem here.

Question: how can I create unique variables for a function, so when called several times, the variables will contain what they should (not change)

Keep in mind that I have to keep it asynchronous as the loop will be large and will not work. async will hit performance hard.

I have a function that draws elements on a canvas. Then I run this function in a for loop to draw some canvases depending on some data in the array.

so simplified version:

function renderCanvas(canvas, dID) { var mName, bName, sName, tName; this.layerCounter = mainData[dID]['layerCount']; console.debug(designID + " has " + layerCounter + " layers"); /* that gives 2 layers for first item and 3 for second)*/ tctx2.clearRect(0, 0, tc2.width, tc2.height); var imgPath = sName; imgObj = new Image(); imgObj.src = "img/" + imgPath; imgObj.onload = function () { tctx2.drawImage(imgObj, 0, 0, w, h, 0, 0, dw, dh); layerCounter--; console.debug(designID + " has " + layerCounter + " layers"); tctx3.clearRect(0, 0, tc2.width, tc2.height); var imgPath = tName; imgObj = new Image(); imgObj.src = "img/" + imgPath; imgObj.onload = function () { tctx3.drawImage(talphaObj, 0, 0, w, h, 0, 0, dw, dh); layerCounter--; console.debug(designID + " has " + layerCounter + " layers"); }; } } for (var i = 0; i < xArr.length; i++) { var cDID = xArr[i]; renderCanvas(contexts[i], cDID); } 

Any suggestions? I'm new to programming, so I probably miss something very light.

+2
javascript variables local-variables
Jan 07 '14 at 15:36
source share
1 answer

clicking on a javascript function (with asynchronous behavior), for example, you want to use closure:

 //im assuming contexts array is defined some where up here?? for (var i = 0; i < xArr.length; i++) { var cDID = xArr[i]; //the following function will self execute on each loop (function (c, d) { //Insert your renderCanvas function body here //but use variable c and d in this closure. //The values you have passed into this closure //are now 'fixed' in this scope and cannot //be interfered with by subsequent iterations })(contexts[i], cDID); }}); 

Basically, you wrap your function in another area so that at the next iteration of the current asynchronous loop, you cannot overwrite your local variables (I think this is the behavior of variables that are โ€œreplacedโ€ by which you refer)

this gives a good explanation of javascript closure, this can be a confusing subject! - How do JavaScript locks work?

+5
Jan 07 '14 at 15:47
source share
โ€” -



All Articles