Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

398
Visualizações
How do I fetch an endpoint on interval, stop the interval, and abort the call on leaving page

I am fetching messages every second after the previous call was successful. The problem is, sometimes it takes 2 seconds for the call to finish. During that time, I can navigate back, choose another person and open the conversation with him.

Now, the previous call is successful and populates the area with both conversation data from UserA, and UserB. Furthermore, it continuously fetches the conversations for both UserA, and UserB.

I am suspecting that perhaps I should use clearTimeout(interval) instead of clearTimeout(fetchConversationInterval), or use better code?

But also, how can I abort the still unfinished call if the user navigates back while the messages are being fetched?

I have the following code:

In data()

fetchConversationInterval: null,

On mounted():

this.messagesFetchingInterval()

And on beforeDestroy()

clearTimeout(this.fetchConversationInterval)

In methods:

async messagesFetchingInterval () {
  let that = this
  this.fetchConversationInterval = setTimeout(async function interval () {
    await that.getConversation(that.peerProfile.user_id)
      .finally(()=> {
        if (that.currentRoute === '/direct-messages/conversation') {
          that.fetchConversationInterval = setTimeout(interval, 1000)
        }
      })
  }, 1000)
},
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Async functions (in your case - getConversation) returns their subscription. you can save it in a parameter and then unsubscribe it in on destroy.

var mySubscription;

this.mySubscription = someAsyncFunc().subscribe((result) => {
   console.log(result);
})

ngOnDestroy(){
   this.mySubscription.unsubscribe();
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda