JS - How to clear interval after using setInterval() [duplicate]

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;

Answers:

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

clearInterval(interval);
Answer

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

For example:

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);
Answer

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.

Answer

You need to use the clearInterval function

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.