简体   繁体   English

多次运行 Mathrandom

[英]Run Mathrandom multiple Times

I have a setTimeout function which prints a random number.我有一个setTimeout function 打印一个随机数。 However, when I run the snippet multiple times in a row in quick succession, the same random number is printed.但是,当我快速连续多次运行代码段时,会打印相同的随机数。

Where am I doing wrong?我哪里做错了?

Here is my function:这是我的 function:

 function generateRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } var t = generateRandomNumber(5000, 10000); setTimeout(function() { console.log("RandomNumber" + " " + t); }, t);

You are seeing the same result when you run the snippet multiple times because the value of t is being changed every time but the value is not immediately printed .多次运行该代码段时,您会看到相同的结果,因为t的值每次都在更改,但不会立即打印该值 Thus, when the timeouts run after t milliseconds, t will have already been set to the last randomly generated value.因此,当超时在t毫秒后运行时, t将已经设置为最后一个随机生成的值。

See the following, which demonstrates what is going on:请参阅以下内容,它演示了正在发生的事情:

 function generateRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } var t; function test(){ t = generateRandomNumber(5000, 10000); console.log(`t set to ${t}`) setTimeout ( function () {console.log("RandomNumber"+" " + t);}, 1000 ); } test() test() test()

You can solve this by storing t privately, inside a function for instance:您可以通过将t私下存储在 function 中来解决这个问题,例如:

 function generateRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } function test() { var t = generateRandomNumber(5000, 10000) setTimeout(function() { console.log("RandomNumber" + " " + t); }, t); } test() test() test()


To log one after the another with random times ( as requested ), you can call setTimeout recursively:要以随机时间( 根据要求)一个接一个地记录,您可以递归调用setTimeout

 function generateRandomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } const send = () => { const t = generateRandomNumber(100, 1000) setTimeout(() => { console.log("Message: " + t) send() }, t) } send()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM