Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setInterval with random number of milliseconds each time?

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

like image 383
smotru Avatar asked Jul 16 '13 14:07

smotru


People also ask

How do you pass parameters to setInterval?

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.

What is the minimum time setInterval 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.

What is difference between setInterval and setTimeout?

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.

Does setInterval run immediately?

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.


2 Answers

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
}
like image 98
3 revs, 2 users 92% Avatar answered Nov 15 '22 10:11

3 revs, 2 users 92%


    setInterval(function() {
//your code to be executed every random miliseconds
} ,random_interval());


var random_interval=function(){
return Math.random()*1000;
}
like image 37
HIRA THAKUR Avatar answered Nov 15 '22 08:11

HIRA THAKUR