Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number every n second js

How can you generate a new random number every given second using Math.random()? I have tried putting it in a function and return Math.random but it return the same thing every time. Is there an efficient way to do this in short amount of code? -thanks

like image 638
Pixeladed Avatar asked Dec 20 '22 01:12

Pixeladed


2 Answers

 setInterval(function(){   
    console.log(Math.floor((Math.random()*100)+1)); 

 }, 1000);

I ran it in Firefox and it works great.

I will follow TryHunter and edit that the "*100" makes it return 1 to 100, and if you want to say 1 to 1000 change it to 1000.

like image 149
bresleveloper Avatar answered Jan 06 '23 10:01

bresleveloper


Try this:

setInterval(function(){ 
    number = Math.floor((Math.random()*100)+1);
    //other code
}, 1000);

Math.random()*100)+1 calculate a number between o and 100, if you want a different range change the number 100 with 10 for example and you can have a range between 0 to 10

like image 22
Alessandro Minoccheri Avatar answered Jan 06 '23 11:01

Alessandro Minoccheri