为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

跃然一笑 2022-10-27 14:47:33
有没有办法在随机秒后将数字增加 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()


查看完整回答
反对 回复 2022-10-27
?
翻翻过去那场雪

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)


查看完整回答
反对 回复 2022-10-27
  • 2 回答
  • 0 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号