Error in function for load bar using a while () {}

0

I am trying to mount a load bar that starts after 2 seconds of loading document , It every 100 milliseconds gets 1% width . However, when the page loads, console.log () shows that the function is running, but nothing happens. How can I fix the problem?

$(document).ready(function(){
    setTimeout(function(){
        var count = 0;
        while(count < 100){
            setTimeout(function(){
                $("#loader-progress").css({"width":count + "%"})
            },500)
            count++;
        }
    },2000);
});
    
asked by anonymous 08.03.2017 / 14:41

2 answers

1

Each call to this code snippet:

setTimeout(function(){

       $("#loader-progress").css({"width":count + "%"})
       count++;
},100)

will have the value of count set to zero. That is, you entered an infinite loop, since count will never be incremented in the correct context.

In order to correct your code, I have changed its setTimeout inside by a setInterval , which will call the function repeatedly, in the following example:

$(document).ready(function(){
    setTimeout(function(){
            var count = 0;
            var idIntervalo =  setInterval(function(){
                            if(count == 105){ clearInterval(idIntervalo); }
                            $("#loader-progress").css("width", count + "%");
                            count++;
            }, 100);
    },2000);
});

idIntervalo is required as this is the only way to stop calls when you reach the goal, using the clearInterval method.

You can check out a working example at the link below

link

    
08.03.2017 / 15:11
0

Well, after a while trying, I was able to solve the problem, I marked @ArturTrapp's answer as right, because it gave me the correct direction to solve the problem.

Well, the code has been reworked for

$(document).ready(function(){
    setTimeout(function(){
        var count = 0;
        setInterval(function(){
            while(count !== 100.5){
                $("#loader-progress").css({"width":count + "%"})
                count = count + 0.5;
            }
        },10);
    },2000);
});

However, a problem occurs, it plays from $("#loader-progress") from 0% to 100% soon in the first loop . But, just by replacing% with%, by% with%, it works perfectly in% with% placed, and then:

$(document).ready(function(){
    setTimeout(function(){
        var count = 0;
        setInterval(function(){
            if(count !== 100.5){
                $("#loader-progress").css({"width":count + "%"})
                count = count + 0.5;
            }
        },10);
    },2000);
});
  • A while was set as a condition, because if set to if , it would give timer max count !== 100.5 in 100 since width would need to be different from 99.5% to that $("#loader-progress") was executed
08.03.2017 / 19:02