Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure for setInterval function in javascript

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.

like image 776
user1367401 Avatar asked Jun 07 '26 03:06

user1367401


1 Answers

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);
like image 66
blueiur Avatar answered Jun 08 '26 17:06

blueiur