-2

I cannot figure out how to stop my setinterval code. I've seen the other posts on stackoverflow however nothing works.

$(document).ready(function() {
  var content =  tinyMCE.getContent('content').value;
});
var myinterval = setInterval(function() {
  $.get("status.php?id=<?php echo $id; ?>",function(data){     
    val = content.value;
    if (val != data) {
      $.pnotify({
        title: 'Regular Notice',
        text: 'Check me out! I\'m a notice.'
      });
      clear();
    }
  });
}, 1000 * 2 * 1); 

function clear(){
    clearInterval(myinterval);
}
Kody
  • 752
  • 2
  • 11
  • 22
  • 1
    `setInterval()` returns an ID, you should clear the interval using that ID. – Ram Feb 02 '14 at 21:53
  • 1
    In this instance, I wouldn't use a set interval anyway, I would use a setTimeout when the ajax call from $.get is complete, to make sure the previous call has complete before starting the next! – rorypicko Feb 02 '14 at 22:06

2 Answers2

1

You have to capture the interval id and pass it to clearInterval.

var intervalId = setInterval(function() {

and

clearInterval(intervalId);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

setInterval() return unique interval ID which you can pass to clearInterval() to cancels repeated action.

//Capture interval id in a variable
var myinterval = setInterval(function () {
    $.get("status.php?id=<?php echo $id; ?>", function (data) {
        val = content.value;
        if (val != data) {
            $.pnotify({
                title: 'Regular Notice',
                text: 'Check me out! I\'m a notice.'
            });

            //Call clear method
            clear();
        }
    });
}, 1000 * 2 * 1);

function clear() {
    //Call method with defined ID
    clearInterval(myinterval);
}
Satpal
  • 132,252
  • 13
  • 159
  • 168