Patata Pequeña
Patata Pequeña

Reputation: 115

JavaScript Timeout Events at Random Intervals

I am working on a web application (JSF/Primefaces) where there are a number of panels shown, which initially are blocked with a 'loading' message, however I am trying to write some JavaScript to set each panel to unblock randomly after between 1-15 seconds, but not necessarily all at the same time as each other (ie panel 1 might unblock after 8 seconds, panel 2 might unblock after 4 seconds etc).

I've written the following code to do this:

function hideBlockUI() {

    var buiIndex = 0;
    while(true) {
        var buiComponent = PF('bui_' + buiIndex); 

        if (buiComponent != null) {
            (function(buiIndex) { 
                setTimeout(function() {hideBUI('bui_' + buiIndex);}, Math.floor((Math.random() * 15) + 1));
            })(buiIndex);
        } else {
            break;
        }

        buiIndex++;
    }

    PF('poll').stop();
}

function hideBUI(name) {
    PF(name).hide();
}

The behaviour I am seeing is that all the panels unblock at exactly the same time in each run, rather than at different random intervals. I've verified that the name being passed into hideBUI() is correct and the random timeout generated is different, but the behaviour still persists. What am I doing wrong?

Edit: just to note that the components to hide are named bui_0, bui_1 ... bui_n depending on how many panels there are, which is not known until runtime.

Upvotes: 0

Views: 119

Answers (1)

Pablo Lozano
Pablo Lozano

Reputation: 10342

Your problem is you are setting the time with

Math.floor((Math.random() * 15) + 1)

which generates values between 1 and 15. So the longest time the browser is waiting is 15 milliseconds. See the setTimeout documentation

Fix it using

 Math.floor((Math.random() * 15) + 1)*1000 // between 1 and 15 seconds

Upvotes: 1

Related Questions