如何在javascript中处理多个进度条 [英] How should multiple progress bars be handled in javascript
问题描述
我有一些进度条,每个进度条都绑定到div,使用'setTimeouts'进行更新。
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);
编辑:根据要求提供我的一个进度条的工作示例:< a href =http://jsfiddle.net/H4SCr/ =nofollow> http://jsfiddle.net/H4SCr/
Edit: As requested a working example of my one progress bar: http://jsfiddle.net/H4SCr/
然而问题是,我有多个带有进度条的div,它们有自己的数据用于计算进展。这意味着在运行中我说有5个不同的超时运行。
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.
我不是javascript的专家,但肯定有一种方法来构建这个以便与一次性用于所有进度条,或者我目前的方法是最好的方法?
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 ?
注意:我不使用jQuery。我更喜欢用香草javascript来学习!
Note: i don't use jQuery. I prefer to go with just vanilla javascript to learn!
推荐答案
检查一下:
http://jsfiddle.net/MZc8X/11/
我创建了一个包含容器ID及其增量值的对象数组。
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();
希望,它适合你。
这篇关于如何在javascript中处理多个进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!