Use setTimeout
to delay the execution of a function. The first argument is the function to execute, and the second argument is the delay in milliseconds.
Remember that functions are first-class citizens in Javascript, so you can pass a function as an argument to another function. Do not invoke the function (i.e. do not use parentheses) when passing it as an argument.
setTimeout(() => { console.log('Hello, world!') }, 2000)
Or, you can pass a named function:
function sayHello() { console.log('Hello, world!') } setTimeout(sayHello, 2000)
One method is to use nested setTimeout
to create multiple delays. You can also use setInterval
to repeat a function at a specified interval. The first argument is the function to execute, and the second argument is the delay in milliseconds.
function sayHello() { console.log('Hello, world!') } setInterval(sayHello, 2000)
Both setTimeout
and setInterval
return a unique identifier that you can use to cancel the delayed function. Use clearTimeout
to cancel a single delayed function, and clearInterval
to cancel a repeating delayed function.
Timeout example:
const timeoutId = setTimeout(sayHello, 2000) clearTimeout(timeoutId)
Interval example:
const intervalId = setInterval(sayHello, 2000) clearInterval(intervalId)
Use Math.random()
to generate a random number between 0 and 1.
const random = Math.random() console.log(random)
To generate a random number between 0 and the length of an array, multiply the random number by the length of the array and round down using Math.floor
.
const items = ['apple', 'banana', 'cherry'] const randomIndex = Math.floor(Math.random() * items.length) console.log(items[randomIndex])
Unfortunately, Javascript doesn't have a nicer way to generate random numbers within a range, but you can always write helper functions to make your code more readable:
function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min } function sample(array) { return array[randomInt(0, array.length - 1)] } items = ['apple', 'banana', 'cherry'] console.log(sample(items))
Or use a library like Lodash that provides additional utility functions.