closures - why is this line coded like this?
我在看宣传单。
在settimeout中,是否有原因称为
我试过了,它给了我相同的输出。但想知道这是否有意义?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function a(fn, time, context) { var lock, execOnUnlock; return function wrapperFn() { var args = arguments; if (lock) { execOnUnlock = true; return; } lock = true; setTimeout(function () { lock = false; if (execOnUnlock) { wrapperFn.apply(context, args); execOnUnlock = false; } }, time); fn.apply(context, args); }; }, |
函数为作为第一个参数的函数创建包装器,该包装器只能以第二个参数指定的间隔执行。如果您在间隔内再次调用它一次或多次,那么最后一次调用将在间隔之后自动执行。
1 2 3 4 5 6 7 | var f = a(someFunction, 1000, {}); f(1); // this will execute the function f(2); // this will not be executed f(3); // this will be executed after a second setTimeout(function(){ f(4); // this will be executed a half second later (two seconds after the first) }, 1500); |
在间隔结束时自动进行的调用将锁定另一个时间间隔的函数。如果代码调用
1 2 3 4 5 6 7 | var f = a(someFunction, 1000, {}); f(1); // this will execute the function f(2); // this will not be executed f(3); // this will be executed after a second setTimeout(function(){ f(4); // this would be executed immediately (1.5 seconds after the first) }, 1500); |