Provide setInterval id and clear id

How can I provide a specific id setInterval()and then call clearInterval()by id.

$('.notify').each(function () {
    var chkr = $(this).find('span').text();

    if (chkr == 'Offline') {
        if (typeof(clearC) !== 'undefined') {
            clearInterval(clearC);
        }

        // how can i provide the ID of "clearC" below
        clearC = setInterval(function () {
            soundOn();
        }, 500);
    }
    else {
        //how can i clear "clearC" with the ID provided in if statement
        if (typeof(clearC) !== 'undefined') {
            clearInterval(clearC);
        }
    }
});

The problem is when the statement is executed if, then the sound continues. But for the next line, type in the statement else(because "Internet") and clear the interval, although it should not be.

So I'm worried to clear clearIntervalfor a specific line until the text "Online" appears.

+4
source share
4 answers

How about this way?

$('.notify').each(function() {
    var $this = $(this);
    var intervalID = $this.data('intervalID');
    var chkr = $this.find('span').text();

    clearInterval(intervalID);
    if (chkr === 'Offline') {
        $this.data('intervalID', setInterval(function() { soundOn(); }, 500));
    }
});

P.S. undefined, , .

+1

, , . Id , jQuery.data:

clearC = setInterval(function () { soundOn(); }, 500);
$(this).data("intervalId", clearC);

:

clearInterval($(this).data("intervalId"));
+1

clearC {}, .id setInterval() .interval. , clearC.id.

var clearC = {};
// ...
$('.notify').each(function(){
  var chkr = $(this).find('span').text();

  if(chkr == 'Offline'){
    if(typeof(clearC.interval) !== 'undefined'){
      clearInterval(clearC.interval);
    }

    // this way you can provide the ID of "clearC.interval" below
    clearC.id = "your-id";
    clearC.interval = setInterval(function () {
      soundOn();
    }, 500);
  }
  else{
    // this way you can clear "clearC.interval" with the ID provided in if statement
    if(typeof(clearC.interval) !== 'undefined'){
      if (clearC.id === "your-id")
        clearInterval(clearC.interval);
    }
  }
});
+1

All Articles