ntgCleaner
ntgCleaner

Reputation: 5985

jQuery generate random number at a random time

I am trying to make a plugin. In this plugin, I have two variables; rateMin and rateMax. I would like to generate a random number between these two numbers and use it as a setInterval time. Then once that number is used, make another random number and use that.

Here's a quick example:

var defaults = {
    rateMin: 500,
    rateMax: 2000
}

var options = $.extend(defaults, options);
return this.each(function(defaults){

var rate = Math.floor(Math.random() * (options.rateMax - options.rateMin + 1)) + options.rateMin; // MAKE A RANDOM NUMBER BETWEEN MAX AND MIN
setInterval(function(){
    var rate = Math.floor(Math.random() * (options.rateMax - options.rateMin + 1)) + options.rateMin
    //DO SOMETHING
}, rate);

I was hoping by doing it this way that the rate would override itself with a new number and be used on the next time the setInterval is called. But it is still using only the first number made before the setInterval.

I guess I don't know how to use a variable outside of it's function.

Any suggestions?

Upvotes: 1

Views: 2355

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

Use setTimeout instead of setInterval if you don't want the delay to be the same each time. Also, don't use var rate in the callback if you want it to overwrite the variable in the outer scope. That said, I'd just encapsulate that piece of logic in a function and forget about it.

function getNextRate() {
    return Math.floor(Math.random() * (options.rateMax - options.rateMin + 1)) + options.rateMin;
}

setTimeout(function foo(){
    //DO SOMETHING

    setTimeout(foo, getNextRate());
}, getNextRate());

Upvotes: 4

Related Questions