简体   繁体   English

引用计时器JS的非全局变量

[英]Referencing Non-Global Variable for Timer JS

I have this function. 我有这个功能。

function changeFrame(){
    var time = setInterval(start, 250);
}

and I want to stop it from firing in another function, but haven't been able to figure out how to do it. 并且我想阻止它触发其他功能,但是还无法弄清楚该怎么做。

Do you mean this? 你是这个意思吗

function changeFrame(){
    var time = setInterval(function() {
        // Do stuff
    }, 250);
}

Think it's in the comments. 认为它在评论中。

Ok amended the fiddle to do what you want. 好吧,修正小提琴来做你想做的。 I made time a global var. 我把时间变成了全球变种。 Call clearInterval in stop with the global var http://jsfiddle.net/QNWF4/3/ 使用全局变量http://jsfiddle.net/QNWF4/3/停止调用clearInterval

In order to call clearInterval you need to have the handle returned by setInterval. 为了调用clearInterval,您需要让setInterval返回句柄。 That means something will either be global to the page or global to a containing function in which your script resides. 这意味着某些内容要么对于页面是全局的,要么对于脚本所驻留的包含函数是全局的。

function Timer()
{ 
    var handle = null;
    this.start = function (fn,interval) {
        handle = setInterval(fn,interval);
    };
    this.stop = function ()
    {
        if (handle) { clearInterval(handle); handle = null; }
    };
    return this;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM