任何人都知道如何在特定时间段和特定数字中生成随机数。
因为我想在一分钟内生成7次任意随机数。
我不知道如何使用setInterval或setTimeout在jquery中使用。
任何帮助都会受到赞赏。
全部谢谢
答案 0 :(得分:2)
请参阅评论以获得解释。
/**
* Generate random numbers at an interval
* @param perMinute - The number of numbers to generate per minute
* @param totalNumbers - The total number of numbers to generate
* @param minNumber - The minimum number to be generated
* @param maxNumber - The max number to be generated
*/
function randomNumberAtInterval(perMinute, totalNumbers, minNumber, maxNumber, cb){
var int = 60000 / perMinute;
var count = 0;
var interval = setInterval(()=>{
cb(Math.random() * (maxNumber - minNumber) + minNumber);
count++;
if(count >= totalNumbers) clearInterval(interval);
}, int);
}
// Will generate 7 numbers per minute
// until it has generated 14 numbers (so for 2 minutes)
// between 0 and 10
// and it will log the number to the console.
randomNumberAtInterval(7, 14, 0, 10, function(randomNumber){
console.log(randomNumber);
})