Roy_Dorsthorst Roy_Dorsthorst - 2 months ago 16
HTML Question

"Refreshing" asynchronous page every n seconds inside while loop

I'm trying to let my page "refresh" asynchronous (I'm refreshing a div element which contains a partial view) while

var edit = true
. edit is altered when i click my button which has class: btn. I'm wondering where i should put my code.

Should i put my while loop inside my $(document).ready?
I'm kind off lost because this is ALL new to me.

This is my code:

var edit = true;

while(edit){
window.setInterval(function(){
alert('5 seconds');
}, 5000);
}

$(document).on('click','.btn', function(){
if(edit ? edit = false : true);
}

Answer

You don't need a while for a continous refresh. Just use clearInterval whenever you clicked the button and restart it on next click.

var interval, i = 0;

$('button').click(function() {
    if( interval ) {
        interval = clearInterval(interval);
    }
    else {
      interval = setInterval(function() {
          console.log(++i);
      }, 1000);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>start / stop</button>

As edit to your comment, to start the interval directly I would encapsulate it into a function and use it. Maybe somehow like this:

var interval, i = 0;

function startInterval() {
    if( !interval ) {
        interval = setInterval(function() {
            console.log(++i);
        }, 1000);
    }

    return interval;
}

// start on document load
$(startInterval);

// start / stop on button click
$('button').click(function() {
    interval = interval ? clearInterval(interval) : startInterval();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>start / stop</button>