local variables overwrite in function run multiple times in a loop

孤人 提交于 2019-12-23 19:24:56

问题


Hey I'm having small issue here.

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

keep in mind I have to keep it asynchronous as the loop will be large and not running it async would hit the performance very hard

I have a function which draws items on canvas. Then I run this function in for loop to draw few canvases depending on some data in 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 fairly new to programming so I'm probably missing something very easy.


回答1:


hitting a javascript function (that has asynchronous behaviour) like this you want to be using a 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 are wrapping your function in another scope so that on the next iteration of the now async loop you cannot overwrite your local variables (i think this is the behaviour of variables being 'swapped' that you refer to)

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



来源:https://stackoverflow.com/questions/20975651/local-variables-overwrite-in-function-run-multiple-times-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!