Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should multiple progress bars be handled in javascript

Tags:

javascript

I have a number of progress bars each tied to a div which are updated using 'setTimeouts'.

An example of how it runs is like this :

myDiv._timer = setTimeout(function () {
            func_name(data)
        }, 1);

Edit: As requested a working example of my one progress bar: http://jsfiddle.net/H4SCr/

The question however is, I have multiple div's with progression bars with their own data to use to calculate progression. Which means with say 5 on the go i have 5 different timeouts running.

I'm no expert in javascript, but surely theres a way to structure this to tie to just one time out for all progress bars, or is my current approach the best method ?

Note: i don't use jQuery. I prefer to go with just vanilla javascript to learn!

like image 818
Sir Avatar asked Nov 02 '22 16:11

Sir


1 Answers

Check this out: http://jsfiddle.net/MZc8X/11/

I created an array of objects which contains the container id and its increment value.

// array to maintain progress bars
var pbArr = [{
    pid: 'bar1', // parent container id
    incr: 1 // increment value
}, {
    pid: 'bar2',
    incr: 2
}, {
    pid: 'bar3',
    incr: 3
}, {
    pid: 'bar4',
    incr: 4
}, {
    pid: 'bar5',
    incr: 5
}];

And, then call a function to create a progress bar...

var loopCnt = 1; // loop count to maintain width
var pb_timeout; // progress bar timeout function

// create progress bar function

var createPB = function () {

    var is_all_pb_complete = true; // flag to check whether all progress bar are completed executed

    for (var i = 0; i < pbArr.length; i++) {
        var childDiv = document.querySelector('#' + pbArr[i].pid + ' div'); // child div
        var newWidth = loopCnt * pbArr[i].incr; // new width
        if (newWidth <= 100) {
            is_all_pb_complete = false;
            childDiv.style.width = newWidth + '%';
        } else {
            childDiv.style.width = '100%';
        }
    }

    if (is_all_pb_complete) { // if true, then clear timeout
        clearTimeout(pb_timeout);
        return;
    }

    loopCnt++; // increment loop count

    // recall function
    pb_timeout = setTimeout(function () {
        createPB();
    }, 1000);
}

// call function to initiate progress bars
createPB();

Hope, it works for you.

like image 183
Mohit Pandey Avatar answered Nov 14 '22 06:11

Mohit Pandey