skip to Main Content
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


  1. What if you just called it before starting the animation???

    function sayHello() {
      console.log('hello')
    }
    
    function animate () {
     window.requestAnimationFrame(animate);
    }
    
    sayHello();
    animate();
    
    Login or Signup to reply.
  2. Just define some boolean to detect if the function has been executed or not with isFired variable like this:

    let isFired = false;
    function sayHello () {
      if(isFired) return;
      isFired = true;
      
      console.log('hello')
    }
    
    function animate () {
     sayHello();
     window.requestAnimationFrame(animate);
    }
    
    animate();
    Login or Signup to reply.
  3. 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();

    Version with if instead of the ternary operator ?:

    function once(fn) {
      let called = false, result;
      return (...args) => {
        if (!called) {
          result = fn(...args)
          called = true
        }
        return result
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search