Kemat Rochi
Kemat Rochi

Reputation: 952

How to stop an auto AJAX call?

I have the following AJAX call to an API,

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>

  Auto-ON
  <input id="inp" type="checkbox" data-toggle="toggle" />

  <div id="out"></div>


  <script>

  $('#inp').change(function(){
    if (this.checked) {  

      setInterval(function(){
      $.ajax({
              url: 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL',
              dataType: 'jsonp',
              success: function(results) {
                $("#out").append(results.Status + "<br />");   
              }
      });
    },5000);


    }   
   });

  </script>


</body>
</html>

I want an AJAX call for every 5 seconds if the checkbox is ON. The AJAX calls should stop if the checkbox is OFF. What am I missing here?

Here's a link to what I've got so far - http://jsbin.com/quqazofesu/edit?html,output

Upvotes: 1

Views: 137

Answers (2)

mplungjan
mplungjan

Reputation: 177692

I do not recommend to use interval with Ajax.

Try this:

var getCheck;
function getIt() {
  if (!getCheck) return;
  $.ajax({
    url: '...',
    dataType: 'jsonp',
    success: function(results) {
      $("#out").append(results.Status + "<br />");   
      if (getCheck) {
        setTimeout(getIt,5000);
      }
    }
  });
}

$(function() {
  $('#inp').on("change",function(){ 
    getCheck = this.checked;
    if (getCheck) getIt();
  });
});

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to call clearInterval when this.checked is false. Try this:

var interval;

$('#inp').change(function() {
    if (this.checked) {  
        interval = setInterval(function(){
            $.ajax({
                url: 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL',
                dataType: 'jsonp',
                success: function(results) {
                    $("#out").append(results.Status + "<br />");   
                }
            });
        }, 5000);
    } else {
        clearInterval(interval);
    }
});

Upvotes: 3

Related Questions