0

How to stop interval when the element stops to exist?

This is my code, I just can't get it to work:

            var AmLoadMoreButton = $('.amscroll-load-button');
            var TopSearch = $('#textSearch');
            var isDisabled = TopSearch.prop('disabled');

            window.setInterval(function(){
                if(AmLoadMoreButton.length){
                    LoadMoreProducts();
                    console.log("Load more still exists");
                } else {
                    console.log("that's all, stop now");
                    StopLoadingProducts();
                }
            }, 1000);

            function LoadMoreProducts(){
                if(!isDisabled){
                    TopSearch.prop( "disabled", true );
                    $('#amasty-shopby-product-list').on("click", ".amscroll-load-button", function(){});
                    $('.amscroll-load-button').trigger('click');
                }
            }

            function StopLoadingProducts(){
                console.log("No more products to load");
                TopSearch.prop( "disabled", false );
                clearInterval();
            }

Is that how you stop the interval? The function for "StopLoadingProducts()" is never called. Nothing logged to console, never mind stopping the interval.

Greg
  • 503
  • 5
  • 30
  • Try setting the interval to a value and then pass that value to `clearInterval` – Cfreak Oct 30 '20 at 17:08
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – freedomn-m Oct 30 '20 at 17:11

1 Answers1

0

Try this code

var AmLoadMoreButton = $('.amscroll-load-button');
var TopSearch = $('#textSearch');
var isDisabled = TopSearch.prop('disabled');

var refreshIntervalId = window.setInterval(function(){
    if(AmLoadMoreButton.length){
        LoadMoreProducts();
        console.log("Load more still exists");
    } else {
        console.log("that's all, stop now");
        StopLoadingProducts();
    }
}, 1000);

function LoadMoreProducts(){
    if(!isDisabled){
        TopSearch.prop( "disabled", true );
        $('#amasty-shopby-product-list').on("click", ".amscroll-load-button", function(){});
        $('.amscroll-load-button').trigger('click');
    }
}

function StopLoadingProducts(){
    console.log("No more products to load");
    TopSearch.prop( "disabled", false );
    clearInterval(refreshIntervalId);
}