Javascript JS - 使用 setInterval() 后如何清除间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8266726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:22:32  来源:igfitidea点击:

JS - How to clear interval after using setInterval()

javascriptjquery

提问by Acubi

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

有没有人知道setInterval()在以下用例中使用后如何杀死间隔?

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;

回答by Yes Barry

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

clearInterval(interval);

回答by leo.vingi

You need to use the clearIntervalfunction

您需要使用该clearInterval功能

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

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

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

回答by Jwalin Shah

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

使用清除间隔方法clearInterval();传递您的变量setInterval

For example:

例如:

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);

回答by dylan maxey

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

如果您计划只运行该函数一次,我建议使用Window SetTimeout() 方法,因为它执行一次,从而在一次运行后清除间隔是多余的。