Leo Prud'hom
Leo Prud'hom

Reputation: 33

How to animate a component with two differents intervals in js

I need to animate a mouth on a component named character. What I want to do is to use state named openned to handle my mouth state.

I need the mouth animation to run every 2 seconds to allow the character to speak with interval. The idea is to display text bellow, and the mouth has to moove only when the text appear.

 state = {
openned : false
 }

  handleMouthState = () => {
this.setState({
  openned : ! this.state.openned
});
  }

  animeMouth = () => {
setInterval(this.handleMouthState.bind(this), 100);
  }

  animMouthWithInterval = () => {
setInterval( this.animeMouth.bind(this), 2000 );
  }

  componentDidMount() {
  setTimeout( this.animMouthWithInterval.bind(this) , 6000);
  }

here is the code i've tried, it works well except that the animMouth func continue to run even if it's called with 2 sec interval, I except to stop animation then reload it

Upvotes: 2

Views: 206

Answers (1)

Hemadri Dasari
Hemadri Dasari

Reputation: 33994

  1. Stop doing binding directly in setInterval instead do it in constructor. What happens is that it creates a new function every time your setInterval is triggered which isn’t good. So remove the bindings.
  2. All your functions are arrow functions hence binding isn’t required
  3. Clear the previous timer before doing setInterval

Here is updated code

   state = {
       openned : false
   }

   handleMouthState = () => {
       this.setState({
          openned : ! this.state.openned
       });
   }

  animeMouth = () => {
       if(this.mouthInterval){
             clearInterval(this.mouthInterval);
       }
       this.mouthInterval = setInterval(this.handleMouthState, 100);
  }

 animMouthWithInterval = () => {
     if(this.animeInterval){
             clearInterval(this.animeInterval);
       }
     this.animeInterval = setInterval( this.animeMouth, 2000 );
 }

 componentDidMount() {
     setTimeout( this.animMouthWithInterval,  6000);
 }

Upvotes: 1

Related Questions