In Revealing module pattern of JavaScript how to use setTimeout function?
Here is the 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();
Framework: jQuery 1.5.2
When I execute the output is:
In callTest 0 f
In callTest 1 f
In callTest 2 f
In callTest 3 f
In callTest 4 f
In callTest 5 f
Instead of:
In callTest 0 a
In callTest 1 b
In callTest 2 c
In callTest 3 d
In callTest 4 e
In callTest 5 f
What am I missing? Where am I doing wrong?
I’ve made a few slight modifications to your code which means it now works as you wish it to:
Here’s a working example.