开发者

Check if all percentages in the array were shown

I'm using this Code to show the current progress in my progressbar:

var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;

function initRotateText() {
rotatingTextElement = document.getElementById("percent");
rotatingText[0] = rotatingTextElement.innerHTML;
rotatingText[1] = "5%";
rotatingText[2] = "10%";
rotatingTe开发者_Go百科xt[3] = "15%";
rotatingText[4] = "20%";
rotatingText[5] = "25%";
rotatingText[6] = "30%";
rotatingText[7] = "35%";
rotatingText[8] = "40%";
rotatingText[9] = "45%";
rotatingText[10] = "50%";
rotatingText[11] = "55%";
rotatingText[12] = "60%";
rotatingText[13] = "65%";
rotatingText[14] = "70%";
rotatingText[15] = "75%";
rotatingText[16] = "80%";
rotatingText[17] = "85%";
rotatingText[18] = "90%";
rotatingText[19] = "95%";
rotatingText[20] = "100%";
setInterval(rotateText, 500);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;

It basicly writs a new percentage in span#percent every 500 miliseconds.

The problem is that after the progressbar has reached 100% it starts again with 0%, 5% and so on.

How can I check if the percentages in the array rotatingText till [20] were all shown and then stop the rotation?


Do this instead:

var rotatingTextElement = document.getElementById("percent");
var ctr = 0;

function rotateText() {
  rotatingTextElement.innerHTML = ctr + "%";
  ctr += 5;
  if (ctr <= 100) {
    window.setTimeout(rotateText, 500);
  }
}

rotateText();


There are a few ways you can tidy this up. To answer your question, start by assigning the interval to a variable:

var rotator = null;
...
rotator = setInterval(rotateText, 500);

...

function rotateText() {
  ctr++;
  if(ctr >= rotatingText.length -1) {
    clearInterval(rotator);
  }
  rotatingTextElement.innerHTML = rotatingText[ctr];
}
...

Then instead of resetting the iterator to 0 when it goes out of bounds, clear the interval so it stops changing the value. You'll need to add the -1 so that it stops on rotatingText[length-1] (the last element)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜