开发者

'multithreading' setInterval functions (Javascript)

开发者 https://www.devze.com 2023-02-20 20:27 出处:网络
I\'m tasked with creating a progress bar (ac开发者_运维百科tually, a timer that looks like a progress bar) that will be triggered on a click event. I need multiple bars as a person may click on multip

I'm tasked with creating a progress bar (ac开发者_运维百科tually, a timer that looks like a progress bar) that will be triggered on a click event. I need multiple bars as a person may click on multiple elements that will trigger the progress bar. This is the script I have now:

function createPbar(IDofpBar, timeOut, timeIncrement ) {

            ...grab dom elements and do the math...

    i=0;
    var newWidth = 0;   

    var x = setInterval(function(){
        theBar.style.width = newWidth+"px"
        newWidth = newWidth + bIncrement;
        if (i == counter) {
            clearInterval(x);
        }
        i++
    }, timeIncrement*1000);

}

This works fine until I have more than one on the page at a time. When I trigger the second one, it affects the first one. I'm guessing it's due to reassigning the variables each time I trigger a new progress bar.

Is there a way to isolate the variables per call?


Use var to declare variables within the scope of the current function, rather than in the global scope. You're missing a var before the i=0; statement. I don't see the code that initializes theBar, but you might be missing a var there, too.

function createPbar(IDofpBar, timeOut, timeIncrement ) {

    /* ...grab dom elements and do the math... */

    var theBar = ...,
        i=0,
        newWidth = 0;

    var x = setInterval(function(){
        theBar.style.width = newWidth+"px"
        newWidth = newWidth + bIncrement;
        if (i == counter) {
            clearInterval(x);
        }
        i++
    }, timeIncrement*1000);
}

Just in case: var keyword @ MDC.


Matt's answer is correct, but I'll expand on it a bit further.

In javascript assigning a variable without using the var keyword creates the variable in the global scope. In your current code this means that all instances of your progress bar are going to be referencing and accessing the same instance of i.

By using the var keyword to declare variables inside of a function, it declares the variable to have local scope and makes it only accessible from within the function. This allows you to have independent versions of the variables used in your function.

This is a gotcha which I often find myself having to go back and fix when I forget.

0

精彩评论

暂无评论...
验证码 换一张
取 消