Randomize setInterval ( How to rewrite same random after random interval)

Here is a really clean and clear way to do it:

http://jsfiddle.net/Akkuma/9GyyA/

function doSomething() {}

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function() {
            doSomething();
            loop();  
    }, rand);
}());

EDIT:

Explanation:
loop only exists within the immediately invoked function context, so it can recursively call itself.

Leave a Comment