【发布时间】:2017-03-22 01:50:30
【问题描述】:
您好,我正在尝试了解 javascript 中的节流。 我有这个代码
function runOnce(fn, ms) {
if(typeOf(fn) !== "function")
return;
ms = ms || 5000;
var active;
return (function() {
if(active) {
console.log('no hurry please');
} else {
active = setTimeout(fn, ms);
}
})();
};
我想使用两个不同的回调函数进行测试
function x() {
console.log('timeout from x');
}
function y() {
console.log('timeout from y');
}
现在这是我的问题:
多次调用runOnce(x);runOnce(x);runOnce(x);,油门函数似乎没问题(只调用function x一次)
- 但是为什么 "console.log('no rush please');" 永远不会被调用?
当我调用runOnce(x);runOnce(x);runOnce(y);runOnce(y); 时,函数 x 和 函数 y 只被调用 1 次,这很好。
- 但是为什么如果我调用
runOnce(x);runOnce(y);runOnce(x);runOnce(y);,function x 和 function y 都会被调用 2 次?
谢谢
【问题讨论】:
-
这真的是你得到的功能吗?它不起作用,也不能用来限制任何东西。
-
"当我调用 runOnce(x);runOnce(x);runOnce(y);runOnce(y); 函数 x 和函数 y 只被调用 1 次,很好" -> 不:jsfiddle.net/vpsvdts8 -> How do JavaScript closures work?
-
@Kaiido
runOnce只返回undefined -
@Andreas,是的,完全误读了...缩进...
-
怎么会??...对不起,让我再检查一遍
标签: javascript closures throttling