1

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?

4

1 に答える 1

4

遅延を毎回同じにしたくない場合は、setTimeout代わりに使用します。setIntervalまた、var rate外側のスコープの変数を上書きする場合は、コールバックで使用しないでください。そうは言っても、そのロジックの一部を関数にカプセル化して、忘れてしまいます。

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

setTimeout(function foo(){
    //DO SOMETHING

    setTimeout(foo, getNextRate());
}, getNextRate());
于 2013-03-20T17:53:48.117 に答える