Join my Laravel for REST API's course on Udemy 👀

Timeout for a random amount of seconds in JavaScript

April 30, 2021  ‐ 1 min read

Waiting is boring but with some randomness I might become a little more fun. In JavaScript you use the setTimeout function to run some code in X amount of milliseconds.

setTimeout(() => {
  window.alert("Done waiting");
}, Math.floor(Math.random() * 10000));

With Math.random() we get random floating point number between 0 and 1, including 0. On order to get from a floating point number between 0 and 1 to a proper amount of milliseconds we multiply by 10000, which will give us a timeout in a range between 0 seconds and 10 seconds.

When the timeout finished the callback function, passed as the first parameter to setTimeout, is called.