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 = true;
}
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?
3
Answers
What if you just called it before starting the animation???
Just define some boolean to detect if the function has been executed or not with
isFired
variable like this:You can define a helper
once
to wrap yoursayHello
. The higher-order function takes a function as an argument and return a new function that will run only onceVersion with
if
instead of the ternary operator?
: