【问题标题】:setinterval() looping at random timessetinterval() 随机循环
【发布时间】:2022-09-24 02:31:36
【问题描述】:

我正在尝试使用setinterval() 函数循环一次并随机花费时间来调用和运行一个名为main() 的函数。

更新代码...

索引.html

    <!DOCTYPE html>
<html lang=\"en\" dir=\"ltr\">
  <head>
    <meta charset=\"utf-8\">
    <title>Links</title>
    <link rel=\"stylesheet\" href=\"style.css\">
  </head>
    <a href=\"settings.html\">
      <button>click here</button>
    </a><br>
    <a href=\"https://github.com/shanegibney/link-two-pages\">
      <button>Back to repository</button><br>
      <canvas id=\"myCanvas\" width=\"300\" height=\"300\"></canvas>

<script>
// Set timeout function
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));

// Random cycle async function
const randCycle = async (mc, ms) => {
  // Run loop for max cycles
  for(let i = 1; i <= mc; i++) {
    // Generate random from ms limit
    const rms = Math.floor(Math.random() * ms);
    // Await for timeout
    await timeout(rms);
    // Log timeout ms
    console.log(`[${i}] ping in ${rms} ms`);
  }
}

// Run 9 random cycles with 4000 ms limit
randCycle(9, 4000);
  </script>
</html>

这段代码有什么问题?它应该以 1、2、3 或 4 秒的间隔随机注销 LOG 次。

这是最好的方法还是我应该使用each()

  • 我认为您需要致电clearInterval 来销毁旧计时器。
  • 当前行为与预期行为有何不同?
  • 它实际上没有工作或输出任何东西。但是感谢大家看这个,我会尝试 clearinterval()。
  • 也许使用 setTimeout 而不是 setInterval 因为它被一遍又一遍地调用。另外,为什么要调用 draw() 两次?只要一次就可以了。所有这些结合在一起使这个功能呈指数增长

标签: javascript random setinterval


【解决方案1】:

另外作为一个选项,您可以使用带有async/await 功能的for 循环,而不是常规的setInterval 功能:

// Set timeout function
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));

// Random cycle async function
const randCycle = async (mc, ms) => {
  // Run loop for max cycles
  for(let i = 1; i <= mc; i++) {
    // Generate random from ms limit
    const rms = Math.floor(Math.random() * ms);
    // Await for timeout
    await timeout(rms);
    // Log timeout ms
    console.log(`[${i}] ping in ${rms} ms`);
  }
}

// Run 9 random cycles with 4000 ms limit
randCycle(9, 4000);

【讨论】:

  • 我看到您使用 for 循环和承诺。您的代码正在此站点上运行,但我无法让它在我自己的计算机上运行,​​就像上面一样。
  • @ShaneG 你想如何在你的情况下运行它 - 登录到控制台或在页面上显示一些东西?因为如果我从您更新的问题中运行 HTML,我会得到控制台输出
猜你喜欢
  • 2017-03-28
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
  • 2016-12-29
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
相关资源
最近更新 更多