$(setInterval (function() { if ( $("#online_counter").html() == 1) { $("wrapper").hide(); } if ( $("#online_counter").html() == 2) { window.location.replace(document.location.href); $("wrapper").show(); } }, 3000 )); 

Dear, is it possible to stop the execution of setInterval using jQuery when condition 2 is satisfied?

  • Can. But only without jQuery because there are no timers in jQuery. - Dmitriy Simushev
  • var timer = setInterval(...); clearInterval(timer); why, do you still overload the page? - Igor
  • @Igor, this is not jQuery! :) - Dmitriy Simushev
  • @DmitriySimushev And I already was going to use this as an answer. Thanks for warning! - Igor

1 answer 1

The body of the second condition ( if ( $("#online_counter").html() == 2) { is it the same?) Reloads the page, which already speaks of bad code and approach. Assign the interval ID to a variable and clear it:

 $(function() { let id = setInterval(function() { // setInterval возвращает уникальный ID вида: 3681 if ($("#online_counter").html() == 1) { $("wrapper").hide(); } if ($("#online_counter").html() == 2) { clearInterval(id); // Функция уничтожения интервала по ID $("wrapper").show(); } }, 3000) }); 
  • And you are very good mister. - Bim Bam
  • the timer will heat up the page nehily, so a warning, on the phone will land the battery if not cut down - Serge Esmanovich
  • @BimBam, I'm confused :) - user207618
  • @SergeEsmanovich, like any code, the interval just runs regularly. But here once in 3 seconds and a simple check is not the worst thing that can be. But, of course, it is necessary to clear it, but it is better to avoid it altogether (intervals are insidious); a similar problem could be solved with the help of the DOM MutationObserver . - user207618