I am trying to create a greeting UI that fades out before displaying main content.The desired effect can be found HERE
When a certain scroll input, say 100px from the top, is reached
I achieved this effect with setTimeout but I now want to know how to set clearTimeout properly.
Here is my code
componentDidMount() {
    window.addEventListener(
      "wheel",
      () => requestAnimationFrame(this.handleScroll.bind(this)),
      false
    );
  }
handleScroll(e){  
    const scrolltop = window.scrollY; 
    scrolltop > 120 ? this.showGreeting().bind(this):null
  }
showGreeting(){
    this.setState({
      greetingDisplay:true,
    })
    const timer = setTimeout(this.showContent.bind(this),5000);
  } 
showContent(){
    this.setState({
      greetingDisplay:false,
      contentDisplay:1,
   })
  //How do I clear the timer here? 
}
In showGreeting,you are setting timeout and storing it in local const varibale.Instead bind it to component instance i.e. this.
constructor(){
     this.timer = null;
      //............rest
  }
showGreeting(){
    this.setState({
      greetingDisplay:true,
    })
    this.timer=setTimeout(this.showContent.bind(this),3000);
    ^^^^^^^^^^^
  } 
When showContent is called state is updated which will trigger render and then componentDidUpdate lifecycle.
In the componentDidUpdate, use this.timer to clear timeout.
componentDidUpdate{
   clearTimeout(this.timer);
}
                        You can easily use ES6 arrow functions without side effects like this:
showContent = () => {
   this.setState({
      greetingDisplay:false,
      contentDisplay:1,
   }); 
}
showGreeting = () => {
    this.setState({
      greetingDisplay:true,
    });
    setTimeout( () => this.showContent, 3000 );
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With