Search code examples
javascriptbuttonrefreshintervals

After click on button prevent reloading the page


So, my page automatically reloads after 20 seconds:

window.setInterval('refresh()', 20000);     
function refresh() {
    window.location.reload();
}

So I've added a button and contidion, if its true, page will reload.

if(siteRefreshButton === true){
    window.setInterval('refresh()', 20000);     
function refresh() {
    window.location.reload();
}

function siteRefresh(){
    siteRefreshButton = !siteRefreshButton;
    console.log(siteRefreshButton);
}

My guess is, that after refresh, another interval starts before it can check if siteRefreshButton is true or false. Any idea how can I make it work?


Solution

  • You could check your condition inside the refresh function.

    var siteRefreshButton = true
    
    function refresh() {
      if (siteRefreshButton) {
        window.location.reload()
      }
    }
    
    function siteRefresh() {
      siteRefreshButton = !siteRefreshButton
      console.log(siteRefreshButton)
    }
    
    window.setInterval('refresh()', 20000)