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?
Advertisement
Answer
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).