SetTimeout with popup template

Q Revealing a JavaScript module template , how to use the setTimeout function?

Here is an 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(); 

Frame: jQuery 1.5.2

When I execute the output:

 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:

 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?

+4
source share
3 answers

I made a few small changes to your code, which means that it now works the way you want:

 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(); 

Here is a working example .

+2
source

call the insight setTimeout function to call in the wrong place, but after 1 sec. And when it is called n, it is equal to the last index. You must make n global and increment every time the function is called

 var classA = (function() { var i = 0; var names = ["a", "b", "c", "d", "e", "f"]; var n = 0; var callTest = function() { for (var i in names) { window.setTimeout(function() { callTest2(names[n]); 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(); 
+2
source
  for (var n in names) { window.setTimeout(function() { callTest2(names[n]); }, 1000); } 

The code above is equivalent to the code below.

  callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); 

Why..? The reason is the call to callTest2 () after one second has ended, but before the entire array of names [] has already been iterated and the last character "f" is passed to callTest2.

An iteration with a very small fraction of a microsecond is used for the loop. those. an array of names [] will be skipped in a very short time. At the end, the last character remains as "f", i.e. Names [n].

+1
source

Source: https://habr.com/ru/post/1390837/


All Articles