简体   繁体   中英

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/

In order to call clearInterval you need to have the handle returned by 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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