Closure for setInterval function in javascript

后端 未结 2 1790
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 03:39

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:

相关标签:
2条回答
  • 2021-01-14 04:09

    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);
    
    0 讨论(0)
  • 2021-01-14 04:10

    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 讨论(0)
提交回复
热议问题