简体   繁体   English

如何使用 jquery 在随机秒后将数字增加 1?

[英]how to increase a number by 1 after random seconds using jquery?

Is there any way to increase a number by 1 after random seconds.有没有办法在随机秒后将数字增加 1。 For example, the base value is 10. So it will change by 1 after a random seconds(ie. 1/2/3/4/5 seconds randomly).例如,基值是 10。所以它会在随机秒后变化 1(即随机 1/2/3/4/5 秒)。

i have tried like this:我试过这样:

var startVal = 10;
setInterval(function(){
    var theVal = startVal + 1; 
    startVal = theVal;
}, Math.round(Math.random() * (6000 - 2000)) + 2000);

Number is increasing but the time is not random.数量在增加,但时间不是随机的。 Please help.请帮忙。

Here is a working example.这是一个工作示例。 Will raise the number by one after 0,1 or 2 seconds将在 0,1 或 2 秒后将数字加一

let number = 10;

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
function addNumber() {
  number++;
  console.log(number)
}
setTimeout(addNumber, getRandomInt(3) * 1000)

If you want the time to change on each iteration, you will need to use setTimeout.如果您希望在每次迭代中更改时间,则需要使用 setTimeout。

 var startVal = 10; function increase() { setTimeout(function(){ var theVal = startVal + 1; startVal = theVal; increase(); console.log(startVal); }, Math.round(Math.random() * (6000 - 2000)) + 2000); } increase()

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

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