12

Is there anyone know how to kill interval after using setInterval() in the following use case?

Thanks in advance!

$(document).ready(function(){
  setInterval(function(){
    $.ajax({ url: "test.php",
      success: function(result){
        $("#results").append(result);
      }
    });
  }, 1000);
});

test.php

$CT = date('Y-m-d H:i:s', time());
echo $CT;
Yes Barry
  • 9,514
  • 5
  • 50
  • 69
Acubi
  • 2,793
  • 11
  • 41
  • 54

4 Answers4

23
var interval = setInterval(function() {
    $.ajax({
        url: "test.php",
        success: function(result) {
            $("#results").append(result);
        }
    });
}, 1000);

clearInterval(interval);
Yes Barry
  • 9,514
  • 5
  • 50
  • 69
  • Thanks @mmmshuddup, but there is nothing displayed on the page after using the code. – Acubi Nov 25 '11 at 10:17
  • 1
    Well you're not supposed to `clearInterval()` _right away_. How many times do you need that to run? – Yes Barry Nov 25 '11 at 11:13
  • 2
    I get the feeling that you mean to use `setTimeout()` instead. In which case, it would only run once and then you wouldn't need to clear anything.. – Yes Barry Nov 25 '11 at 11:14
8

You need to use the clearInterval function

    var interval = setInterval()....
    clearInterval(interval);

http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/

leo.vingi
  • 1,842
  • 12
  • 17
5

Use clear interval method clearInterval(); pass your variable in which you setInterval.

For example:

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);
Yes Barry
  • 9,514
  • 5
  • 50
  • 69
Jwalin Shah
  • 2,451
  • 1
  • 17
  • 22
0

If you were planning on only running the function once, I would suggest using Window SetTimeout() Method as it executes once, making clearing the interval after one run redundant.

dylan maxey
  • 67
  • 1
  • 3