最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Generate random number every n second js - Stack Overflow

programmeradmin0浏览0评论

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

Share Improve this question asked Aug 22, 2013 at 13:14 PixeladedPixeladed 1,8015 gold badges16 silver badges27 bronze badges 3
  • 1 Math.random return a number between 0 and 1. Are you aware of that fact? – Marc Commented Aug 22, 2013 at 13:17
  • Just put the Math.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
  • What was the value of "same thing every time"? – chux Commented Aug 22, 2013 at 17:00
Add a comment  | 

4 Answers 4

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

发布评论

评论列表(0)

  1. 暂无评论