The function showRandom
is executed every 1000 milliseconds but i want it to be executed every random
milliseconds.. is there any solution for this ? Thank you!
var random = 1000;
setInterval(function() {random = randomizator(60000,200000);} ,1000);
setInterval(function() {showRandom(random);}, random);
function randomizator(a,b)
{
return Math.floor(Math.random()*b) + a;
}
function showRandom(random)
{
$('#test').text(random);
}
DEMO: jsFiddle
The setInterval() method can pass additional parameters to the function, as shown in the example below. setInterval(function, milliseconds, parameter1, parameter2, parameter3); The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
To mitigate the potential impact this can have on performance, once intervals are nested beyond five levels deep, the browser will automatically enforce a 4 ms minimum value for the interval. Attempts to specify a value less than 4 ms in deeply-nested calls to setInterval() will be pinned to 4 ms.
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.
Felix said it: If you want to change the interval every time, use setTimeout
instead. Simplified example as I'm having trouble following exactly what you want your original code to do:
doTheRandom();
function doTheRandom() {
random = randomizator(60000,200000);
// Up to 1 second
setTimeout(doTheRandom, randomizator(1000, 2000)); // 1-2 seconds
}
setInterval(function() {
//your code to be executed every random miliseconds
} ,random_interval());
var random_interval=function(){
return Math.random()*1000;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With