最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Closure for setInterval function in javascript - Stack Overflow

programmeradmin3浏览0评论

How to use setInterval without using global variables? I'd prefer to wrap all variables of function invoked by setInerval in some kind of closure, like so:

var wrap = function (f){
 var local1, local2, ...;
 return function () { return f(); }
}

This doesn't work, but the idea is that I'd pass wrap(f) instead of f to setInterval, so that locals for f are nicely wrapped and don't pollute the global scope.

How to use setInterval without using global variables? I'd prefer to wrap all variables of function invoked by setInerval in some kind of closure, like so:

var wrap = function (f){
 var local1, local2, ...;
 return function () { return f(); }
}

This doesn't work, but the idea is that I'd pass wrap(f) instead of f to setInterval, so that locals for f are nicely wrapped and don't pollute the global scope.

Share Improve this question asked Aug 3, 2012 at 17:25 user1367401user1367401 1,0501 gold badge17 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

javascript don't have dynamic binding.(except this keyword)

use anonymous function can archive your idea. (it called closure)

var fnc = function(){
    var local1, local2;

    return function(){
         // using local1, local2
    }
};

setInterval(fnc, 1000);

I assume you're looking for something like this...

var wrap = function (f){
    var locals = Array.prototype.slice.call(arguments, 1);
    return function () { f.apply(this, locals); }
};


function logger_func() {
    console.log.apply(console, arguments);
}

for (var i = 0; i < 10; i++) {
    setTimeout( wrap(logger_func, i, "foo_" + i), // <-- wrapping i
                i * 1000 );
}

Note that modern environments let you pass extra arguments to setTimeout...

for (var i = 0; i < 10; i++) {
    setTimeout(logger_func, i * 1000, i, "foo_" + i);
}
发布评论

评论列表(0)

  1. 暂无评论