Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firing a function ONCE in a animation loop Javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading