在Revealing module pattern javascript的setTimeout函数怎么用?
这是 example .
HTML:<div id="container1"></div>
JavaScript:
var classA = (function() {
var i = 0;
var names = ["a", "b", "c", "d", "e", "f"];
var callTest = function() {
for (var n in names) {
window.setTimeout(function() {
callTest2(names[n]);
}, 1000);
}
};
var callTest2 = function(pName) {
$("#container1").append("In callTest " + i+++" " + pName + "<br>");
window.setTimeout(function() {
callTest2(pName)
}, 10000)
};
return {
testTheTest: function() {
callTest();
}
}
})();
classA.testTheTest();
框架:jQuery 1.5.2
当我执行时输出是:
In callTest 0 f
In callTest 1 f
In callTest 2 f
In callTest 3 f
In callTest 4 f
In callTest 5 f
代替:
In callTest 0 a
In callTest 1 b
In callTest 2 c
In callTest 3 d
In callTest 4 e
In callTest 5 f
我错过了什么?我哪里做错了?
最佳答案
我对您的代码做了一些细微的修改,这意味着它现在可以按您希望的方式工作:
var classA = (function() {
var i = 0,
names = ["a", "b", "c", "d", "e", "f"],
namesLength = names.length,
callTest = function() {
window.setTimeout(function() {
callTest2(0);
}, 1000);
},
callTest2 = function(pIndex) {
if (pIndex < namesLength) {
var name = names[pIndex++];
$("#container1").append("In callTest " + i+++" " + name + "<br>");
window.setTimeout(function() {
callTest2(pIndex);
}, 1000);
}
};
return {
testTheTest: function() {
callTest();
}
}
})();
classA.testTheTest();
这是一个 working example .
关于javascript - setTimeout 与揭示模块模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8851260/