Home > Software engineering >  setTimeout Polling crashed for intermittent internet connection
setTimeout Polling crashed for intermittent internet connection

Time:06-16

Hi I have a polling in javascript:

setTimeout(function () {
  document.querySelector("input[type='submit']").click();
}, 5000);

But when a user got suddenly lost or has intermittent internet connection. The polling crashed. Any workaround to solve this issue?

CodePudding user response:

What you're doing isn't really polling (as in periodically checking for updates and only performing an action if there was something to do). It's just periodic refreshing of the page, by submitting it and hoping to get back a page that keeps the refresh.

A page submit is a navigation, which causes your JavaScript state to be lost. This means that if your navigation lands on an error page, either due to network problems or to an issue on the server, you'd be landing on a page that won't have any code to refresh/navigate automatically, and you'd also lose your JavaScript context, including any timers or any chance to remediate the situation.

If you want to make your app resilient to network and server problems, you'll need to use a different programming model to call the network — one that doesn't involve navigations, so that the JavaScript context is kept, allowing retry code to continue running until success. You'll have to use something like an AJAX request to get the new content of the page and update the DOM, all using JavaScript.

There are plenty of guides on how to use AJAX (for example this one).

CodePudding user response:

You want setInterval if you want it to repeat every 5 seconds (the interval). Only use setTimeout when you want something to happen once, after a time-out.

I suspect likely looks like it keeps working because the page probably refreshes after submission, starting the entire script over from the very start. It's like turning it off-and-on again.

  • Related