Delaying a loop in JavaScript
One interesting problem I came across recently was delaying the execution of a loop in my JavaScript code. In my use case, I was creating an animated drawing effect on a html canvas using an array of data points. With no delay, the browser is simply too quick at parsing the data points, so I introducted a small 10 ms as a visual cue.
While other languages have some built in libraries to work with time, JavaScript has no such equivalent.
# Python
import time
time.sleep(3) # Sleep for 3 seconds
..or in Java
// Java
Thread.sleep(1000)
The JavaScript solution involves uses the Promise API and a standard setTimeout call to force the calling function to wait for a specified amount of time before continuing.
Here it is using es5 syntax
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
…and the same thing as an arrow function
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
Finally, call the method from inside your function
const myFunction = async () => {
for (let j = 0; j < stroke.points.length; j++) {
await sleep(100) // ms
}
}
One gotcha is that it will not work with the autolooping of .forEach, .map, .filter and .reduce. This is due to there incompatability with async/await. These methods work by invoking the callback function for each array element, but it does not wait for each call to end before finishing the entire forEach cycle. This will mess up our timing. In this case use a for() loop or a for…in…