【问题标题】:how to increase a number by 1 after random seconds using jquery?如何使用jquery在随机秒后将数字增加1?
【发布时间】:2020-07-01 13:19:26
【问题描述】:

有没有办法在随机秒后将数字增加 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);

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

【问题讨论】:

  • 请访问help center,使用tour查看内容和How to Ask。做一些研究,搜索关于 SO 的相关主题;如果您遇到困难,请发布您的尝试minimal reproducible example,并使用[<>] sn-p 编辑器记录输入和预期输出。
  • RTM
  • jQuery 本身不会用于此。在 JavaScript 中,你可以增加一个数字,你可以生成一个随机数,你可以设置一个操作的延迟。您尝试了哪些方法,哪些方法无效?
  • 你有没有尝试过像setTimeout()Math.random()这样的简单函数?
  • 您的代码到底有什么问题?

标签: javascript jquery random


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是一个工作示例。将在 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)
    

    【讨论】:

      猜你喜欢
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      相关资源
      最近更新 更多