Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if page is loading in JavaScript?

I have a setInterval that selects an input and then submits the form with a click action. Now my problem is that my function clicks the button too many times. I tried adding a boolean to check if it has been clicked. No dice, page won't load. For some odd reason, the submit button doesn't work sometimes. I need the interval to be at 100 - 1000 just in case the page timeouts or lags.

How do I check to make sure it doesn't click again while the page is trying to load? The code can work fine if the interval is above 1000, but I need speed.

var pickSize = setInterval(function(){
    if (window.location.href.indexOf('/website/') == -1 && window.location.href.indexOf('/page.php') == -1) {
        if ($('input[value="236"]').attr("checked", true)) {
            $('.Add').click();
        }
    }
}, 1000);
like image 791
C O Avatar asked Nov 21 '22 23:11

C O


1 Answers

You can use onbeforeunload event to check if the page has started to navigate to another page:

var interval = setInterval(function(){
    if(window.location.href.indexOf("/website/") == -1 && window.location.href.indexOf("/page.php") == -1) {
        if($('input[value="236"]').attr("checked", true)) {
            $('.Add').click();
        }
    }
}, 1000);

window.addEventListener('beforeunload', function() {
  clearInterval(interval);
  console.log('Started to navigate away...');
});

However, it looks like you need to fix causes, but not consequences. Post your HTML and JS into another question like "why does my form submit only sometimes?" and let's try to understand the reason. It definitely does happen for some reason :)

like image 149
Yeldar Kurmangaliyev Avatar answered Dec 25 '22 04:12

Yeldar Kurmangaliyev