有没有办法在随机秒后将数字增加 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);数量在增加,但时间不是随机的。请帮忙。
2 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
如果您希望在每次迭代中更改时间,则需要使用 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()
翻翻过去那场雪
TA贡献2065条经验 获得超14个赞
这是一个工作示例。将在 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)
添加回答
举报
0/150
提交
取消
