I am trying to use the setinterval() function to loop once and take a random amount of time to call and run a function called main().
Updated code...
index.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>
Can anyone see what wrong with this code? It should log out LOG a random amount of times either at 1,2,3 or 4 second intervals.
Is this the best way to do it or should I use each() somehow?
Thanks
CodePudding user response:
Also as an option you can utilize for
loop with async/await
feature, instead of regular setInterval
function:
// 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);