【发布时间】: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