Question: In the following example, this script applies the class 'green' to all 'span' HTML elements randomly, and at a steady rate.

```
var items = $('span').get();
var interval = setInterval(function() {
    var random_number = Math.floor(Math.random() * items.length);
    $(items[random_number]).addClass('green');
    items.splice(random_number, 1);
    if (items.length === 0) {
        clearInterval(interval);
      }
     }, 10);

```

<http://jsfiddle.net/DUbQB/>

I've updated it so that it changes 2 elements per interval, simply by calling the function twice.

```
var items = $('span').get();
var interval = setInterval(function() {

    function rand(random_number) {
    var random_number = Math.floor(Math.random() * items.length);
    $(items[random_number]).addClass('green');
    items.splice(random_number, 1);
    }

    rand(1);
    rand(2);

    if (items.length === 0) {
        clearInterval(interval);
    }
}, 500);

```

<http://jsfiddle.net/DUbQB/3/>

All I want to know is, is there a way to get this script to randomly turn all elements green in the **same time**, regardless of how many elements there are?

For example, <http://jsfiddle.net/DUbQB/3/> completes in ten intervals because there's twenty elements and the random function is called twice. 

But if there were forty elements, the script would take twenty intervals, and so twice as long. How could this script always take the same amount of time to complete, regardless of how many elements there are?

Answer: 
You just have to do small math calculation to determine either how fast to run the interval or how many elements to change per interval.

For example, if you want it to complete in 5000ms, then you just do:

```
var items = $('span').get();
var intervalTime = 5000 / items.length;

```

Then use that `intervalTime` with the `setInterval()` call. This will complete the operation in 5000ms no matter how many spans there are.
<http://jsfiddle.net/CA97a/>

Thanks @JWH give it a timer <http://jsfiddle.net/CA97a/5/>

I think change the timer interval will be more simple

```
<div class="container">
</div>

<script>
// Use for test
for (var i=0; i < 20 /*Count*/; i++) {
    $(".container").append("<span> "+i+" </span>");
}

// Script start
var items = $('span').get();
var interval = setInterval(function() {
    var random_number = Math.floor(Math.random() * items.length);
    $(items[random_number]).addClass('green');
    items.splice(random_number, 1);

    if (items.length <= 0) {
        clearInterval(interval);
    }
}, 5000/items.length); // Finish in 5 sec
</script>

```

I have a another idea, this way time will be more accurate, I have test it with 10K in Firefox, don't feel too much lag
<http://jsfiddle.net/LmE6J/>

```
$("span").each(function () {
    function closure(s) {
        return function () {
            $(s).addClass("green");
        };
    }
    setTimeout(closure(this), (Math.random()*Math.floor(5000)));
});

```