Levan Charuashvili
Levan Charuashvili

Reputation: 163

How can I randomize setTimeout time

I wrote this simple jQuery script to popup my #popup div but not every 2 seoncds or 3 I want time to be generated with Math.random() here's code but unfortunately it doesn't work

$(document).ready(function(){
    function pop(){
            $('#popup').show();
            $('#content').addClass('blur');
        };
    setTimeout(pop,el);
    $('#x').click(function(){
        $('#popup').hide();
        $('#content').removeClass('blur');
    });
var el = Math.floor(Math.random() * 5000);
})

Upvotes: 0

Views: 500

Answers (2)

Twisty
Twisty

Reputation: 30893

As you know, Math.random() will return a number between 0 and 1.

JavaScript Console

>> Math.random()
<- 0.8419219077751203

If you want a larger random number, you can use a multiplier. For Milliseconds, there are 1000 in 1 second, so if we want a random number of Milliseconds, between 0 and 1000, we can multiply the result by 1000.

>> Math.random() * 1000
<- 188.6188679027202

We're essentially just moving the decimal. Now if we want a random number of milliseconds between 2 seconds and 3 seconds, we can add 2000 to compensate. Now instead of being between 0 and 1000, it's between 2000 and 3000.

>> (Math.random() * 1000) + 2000
<- 2494.96714163502

Now you have to make a decision about the remaining decimal content. You can Math.round() or Math.floor().

>> Math.round(2494.96714163502)
<- 2495
>> Math.floor(2494.96714163502)
<- 2494

1 ms should not make a large difference in your timer, so you can use whichever you like.

So if you need a random number of milliseconds from 2 to 3 seconds, you're done. If you need to create more random timers, then see the other posted answer. This creates a Range between 0 and n, where n is not 0 and not less than 0, and a Base (b):

>> Math.floor((Math.random() * (3000 - 2000)) + 2000)
<- 2556

JavaScript

$(function(){
  function getRandomMillisecond(min, max){
    if(max - min <= 0){
      return 1;
    }
    return Math.floor((Math.random * (max - min)) + min);
  }

  function pop(){
    $('#popup').show();
    $('#content').addClass('blur');
  };

  setTimeout(pop, getRandomMillisecond(2000, 3000));

  $('#x').click(function(){
    $('#popup').hide();
    $('#content').removeClass('blur');
  });
});

Hope that helps.

Upvotes: 1

Gutelaunetyp
Gutelaunetyp

Reputation: 1882

function randomIntFromInterval(min, max) // min and max included
{
  return Math.floor(Math.random() * (max - min + 1) + min);
}

randomIntFromInterval(3000, 5000);

This would be a random interval between 3 seconds and 5 seconds.

If you want it in between 2 and three seconds, you would write:

randomIntFromInterval(2000, 3000);

The values (2000, 3000) are milliseconds.

Upvotes: 0

Related Questions