function sayHello () {
consile.log('hello')
}
animate () {
sayHello();
Window.requestAnimationFrame(animate);
}
animate();
Is there a way to make this sayHello function fire only once? Perhaps using async await? Or maybe some completely other way I’m ignorant to. I’d love to learn!
Naive solution:
What I’ve been doing is making some kind of global flag variable.
let saidHello = false;
animate () {
if(saidHello === false) {
sayHello();
saidHello = false;
}
Window.requestAnimationFrame(animate);
}
This works but seems messy and is hard to follow at times. Perhaps there is a best practice for firing a function ONCE in an animation loop?
>Solution :
You can define a helper once to wrap your sayHello. The higher-order function takes a function as an argument and return a new function that will run only once
const once = fn => {
let called = false, result;
return (...args) => called ? result : (called = true, result = fn(...args));
};
const sayHello = once(() => {
console.log('hello');
});
function animate() {
sayHello();
window.requestAnimationFrame(animate);
}
animate();