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

有没有办法在随机秒后将数字增加 1。例如,基值是 10。所以它会在随机秒后变化 1(即随机 1/2/3/4/5 秒)。


我试过这样:


var startVal = 10;

setInterval(function(){

    var theVal = startVal + 1; 

    startVal = theVal;

}, Math.round(Math.random() * (6000 - 2000)) + 2000);

数量在增加,但时间不是随机的。请帮忙。


跃然一笑
浏览 177回答 2
2回答

猛跑小猪

如果您希望在每次迭代中更改时间,则需要使用 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()

翻翻过去那场雪

这是一个工作示例。将在 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript