L
L
lavezzi12017-10-23 12:10:22
JavaScript
lavezzi1, 2017-10-23 12:10:22

What to do with long polling in SPA?

Hello. There are difficulties in organizing long polling. The task is simple, there is data in the table, let's call it items, each item has some kind of state or task that needs to be checked and when it changes on the server, change the status in the table.

checkTask(item) {
        if (!item.active) {
           fetch(`/items/${item.id}/`)
            .then(response => response.json())
            .then((response) => {
              if (!item.active) {
                setTimeout(() => this.checkTask(item), CHECK_INTERVAL);
              } else {
                // Do something here, like toast
                // Clear task
                item.active = true;
              }
            });
        }
      },

This is an example from Vue. This method checks and if the item has become active on the server, then it activates it in our table and that's it. Works perfect. But there is one big problem. When you go to another page via the router, without reloading the page, the checkTask execution continues, because, as far as I understand, you need to clear the setTimeout of each task.
I think that this problem can also be in other frameworks because they are all typical.
What are the solutions?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Negwereth, 2017-10-23
@Negwereth

Clear timeout.

A
Artem0071, 2017-10-23
@Artem0071

yes, you need to clean it, you
can write an array of timeouts to data(), and then do it in the beforeRouteLeave component and clean them there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question