Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

388
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!