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
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
4 Answers
Reset to default 6 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.
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
var number;
(function repeat() {
number = Math.random();
setTimeout(repeat, 1000);
})();
Just
return Math.floor(Math.random()*100)+1;
to get random int number from 1 to 100
Math.random
return a number between 0 and 1. Are you aware of that fact? – Marc Commented Aug 22, 2013 at 13:17Math.random()
expression in the repeatedly executed code instead of before it. Show us what you have tried. – Bergi Commented Aug 22, 2013 at 13:40