Javascript setInterval函数清除自己? [英] Javascript setInterval function to clear itself?

查看:79
本文介绍了Javascript setInterval函数清除自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

myInterval = setInterval(function(){
     MyFunction();
},50);

function MyFunction()
{
    //Can I call clearInterval(myInterval); in here?
}

如果我编码的是,间隔不会停止(不会被清除)上面没问题,那么它会帮我看看其他原因造成的问题。谢谢。

The interval's not stopping (not being cleared), if what I've coded above is fine then it'll help me look elsewhere for what's causing the problem. Thanks.

编辑:我们假设它在调用clearInterval之前完成了几个时间间隔,这样就不再需要setTimeout。

Let's assume it completes a few intervals before clearInterval is called which removes the need for setTimeout.

推荐答案

只要你有保存的 interval 变量的范围,就可以从任何地方取消它。

As long as you have scope to the saved interval variable, you can cancel it from anywhere.

在子范围内:

var myInterval = setInterval(function(){
     clearInterval(myInterval);
},50);

在兄弟范围内:

var myInterval = setInterval(function(){
     foo();
},50);

var foo = function () {
    clearInterval(myInterval);
};

如果超出范围,你甚至可以通过间隔:

You could even pass the interval if it would go out of scope:

var someScope = function () {
    var myInterval = setInterval(function(){
        foo(myInterval);
    },50);
};

var foo = function (myInterval) {
    clearInterval(myInterval);
};

这篇关于Javascript setInterval函数清除自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆