weixin_33720078 2016-04-11 09:09 采纳率: 0%
浏览 12

如何停止自动AJAX通话?

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

  • 写回答

2条回答 默认 最新

  • Memor.の 2016-04-11 09:12
    关注

    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);
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?