DEV Community

Discussion on: Displaying loading animation on Fetch API calls

Collapse
 
shub78910 profile image
Shubham Hirakki

But then, the animation time will be irrespective of the actual loading time, that is, 5 seconds fixed. What if it takes longer or shorter time to load?

Collapse
 
rahul1116 profile image
Rahul Ravindran

You're right. In that case all you need to do is store the timer id which is returned by the setTimeout in a global variable. Later if the response comes earlier than 5 secs, you just need to clear out the timer by adding one line in hideLoading()

clearTimeout( timerId ) // This will clear the timer and the .display class is anyway removed
Enter fullscreen mode Exit fullscreen mode

But in case of late response, you can get rid of the setTimeout logic altogether and it'll work fine