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
- Greeting appears for 5seconds and fades out
- Main content waits until greeting fades out and gets displayed.
I achieved this effect with setTimeout but I now want to know how to set clearTimeout properly.
Here is my code
ponentDidMount() {
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?
}
- Here is my attempt, Codepen
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
- Greeting appears for 5seconds and fades out
- Main content waits until greeting fades out and gets displayed.
I achieved this effect with setTimeout but I now want to know how to set clearTimeout properly.
Here is my code
ponentDidMount() {
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?
}
- Here is my attempt, Codepen
2 Answers
Reset to default 10In showGreeting
,you are setting timeout and storing it in local const
varibale.Instead bind it to ponent 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 ponentDidUpdate
lifecycle.
In the ponentDidUpdate
, use this.timer
to clear timeout.
ponentDidUpdate{
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 );
}