A
A
Andrey Chirkov2021-07-07 17:26:19
JavaScript
Andrey Chirkov, 2021-07-07 17:26:19

How to call an action if the API response is more than X seconds?

Let's imagine that there is an online store.
I need to have 2 event options when going to the category of goods and loading them.

1 - response from API is less than 1 second -> loader is not shown.
2 - response from API is more than 1 second -> loader is shown.

That is, I want to show a conditional loader if the promise response is long,
if the fast response is not to show the loading icon at all.

What for? I want to eliminate the jerking (appearance and disappearance) of the loader with a fast Internet (99% of cases)
and set special conditions for a slow Internet.

Is it possible at all? Google turned up no results.
Or who thought about it I will be glad to hear options for solving a similar problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Ineshin, 2021-07-07
@andreichirkov

You need to run the timer and your request in parallel.
If the request ends earlier, clear the timer and the loader will not appear.

let timerId = setTimeout(() => {
  // show loader
}, 1000);

fetch('API url').then((data) => {
  // prevent loader show
  clearTimeout(timerId);

  // show result
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question