zratan zratan - 3 years ago 134
Javascript Question

How to break setInterval to launch another

I want to auto reload div in my site. If I click to bottom the script reload another div when i use clearInterval to stop

interval1
it not working the script reload again
interval1
,when i use console.log interval i find false and the script reload again clearInterval not working or??

<script type="text/javascript">
var interval2;
var interval1;
$(document).ready(function() {
var get_template = function() {

$("#live-grouped-odds-current").load("template.php");
}
interval2 = setInterval(get_template, 6000);


$("#live_details").click(function() {
clearInterval(interval2);
console.log(interval2);
$('#live-overview-menuitem').removeClass('Actual');
$('#live_details').addClass('Actual');
$("#button_sp").css('display', 'none');
$("#button_dt").css('display', 'block');
clearInterval(interval2);
interval2 = false;
$("#live-grouped-odds-current").empty();
$("#loader12").css('visibility', 'visible');

$("#live-grouped-odds-current").load("details.php");

});
$("#loader12").css('visibility', 'visible');


$.get("details/events.php", function(data1) {
$("#event_list").html(data1);
});

$("#loader12").css('visibility', 'hidden');

var refresh = function() {
$.get("details/events.php", function(data1) {
$("#event_list").html(data1);
});
$.get("details/simple_event.php", function(data) {
$("#simple_event").html(data);
});
}
interval1 = setInterval(refresh, 6000);

});

function simple_event(id) {
clearInterval(interval1);
$('.Event').removeClass('Actual');

$("#" + id).attr('class', 'Actual');
$("#simple_event").empty();
$("#loader12").css('visibility', 'visible');
$.get("details/simple_event.php?id=" + id, function(data) {

$("#simple_event").html(data).hide();
$("#simple_event").slideDown(1000);
//alert( "Load was performed." );
$("#loader12").css('visibility', 'hidden');
});
interval1 = setInterval(refresh, 6000);
}
</script>

Answer Source

When you call clearTimeout it means the interval will not be triggered again, but if $("#live-grouped-odds-current").load("template.php"); is still running it will complete. If $("#live-grouped-odds-current").load("template.php"); takes more time than 6000ms you will begin to do multiple request in parallel as well. (It would be better to use setTimeout I think)

Once you call clearInterval(interval2) the first time, set interval2 to undefined

$("#live_details").click(function() {
    clearInterval(interval2);
    inteval2 = undefined;

and change get_template to

var get_template = function() {
    $.get("template.php", function( data ) {
        if (inteval2 !== undefined) {
            $("#live-grouped-odds-current").html( data );
        }
    });
}

so #live-grouped-odds-current won't be undated if the interval has been cleared

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download