最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - local variables overwrite in function run multiple times in a loop - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Jan 7, 2014 at 16:05 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked Jan 7, 2014 at 15:36 Tomasz GolinskiTomasz Golinski 7286 silver badges29 bronze badges 2
  • if its asynchronous you want to be using a closure here – alfonsob Commented Jan 7, 2014 at 15:41
  • Don't understand your question.. what value you want to assign to that variable ? BTW context[i] is not declared in you code – Merlin Commented Jan 7, 2014 at 15:41
Add a ment  | 

1 Answer 1

Reset to default 8

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?

发布评论

评论列表(0)

  1. 暂无评论