Control width expand onClick while setInterval, js,html5

98 Views Asked by At

I have setInterval problem. I made something similar to load bar. When I click mouse I fire expanding width of my block called loadBar1

// here preset of interval and loadbar...
var interval = 0;
createLoadBar1 = function() {
loadBar1 = {
    // another stuff
    width:0,
};

document.onclick = function (mouse) {
    interval = setInterval(expandLoadBar1, 60);
}

It's expands by the help of this function:

function expandLoadBar1() {
    if(loadBar1.width < 60) {
        loadBar1.width++;
    }
    if (loadBar1.width >= 60) {
        loadBar1.width = 0;
        clearInterval(interval);
    }
}

It's very simple above and works well when I click just once but I start having problems when I click more that one time by mouse clicking, it's logically cause the faster loadBar1.width expanding twice and after second or more mouse click the clearInterval for interval stops working and just continue raising expanding speed when I click more.

1

There are 1 best solutions below

5
On BEST ANSWER

You probably need to clear the interval when the user clicks:

document.onclick = function () {
  clearInterval(interval);
  interval = setInterval(expandLoadBar1, 60);
}