0

I am trying to run a code in which I loop through a function like

$.each(imageArray, function(key, value) {                                                 
    setTimeout(function() {
        functionName(value);
    }, 4000);
});

and the function I am comparising two images through Node.js's resemble.js and its showing values like

[Log] 1--0.00 (main.js, line 69)

[Log] 9 (main.js, line 245)

[Log] 2 (main.js, line 245)

[Log] 4 (main.js, line 245)

[Log] 8 (main.js, line 245)

[Log] 6 (main.js, line 245)

[Log] 7 (main.js, line 245)

[Log] 1 (main.js, line 245)

[Log] 10 (main.js, line 245)

[Log] 3 (main.js, line 245)

[Log] 5 (main.js, line 245)

[Log] 2--34.95 (main.js, line 69)]

I know I am not doing anything wrong but the output shows otherwise. So I am using setTimeout because the function I am using might take time to execute. So my question is can I force my function to loop through synchronously ?

Matt Lishman
  • 1,737
  • 1
  • 19
  • 33
  • `setTimeout()` is asynchronous. – Marcos Pérez Gude Feb 18 '16 at 12:30
  • so what should i use for delay – soCalledDeveloper Feb 18 '16 at 12:30
  • Maybe you need to remove the timeout inside the `each()` and move it to inside the `functionName()` function. The each will fire the function synchronously, and when it enter to the function you notice the delay. – Marcos Pérez Gude Feb 18 '16 at 12:31
  • 1
    What are you attempting to do? All your current code does is execute the `functionName` for every iteration of the loop after a 4000ms (+ processing time) delay. The differing order is because `setTimeout` is asynchronous. – Rory McCrossan Feb 18 '16 at 12:32
  • Nothing -- javascript is nonblocking (which is a good thing). If you're in need of some sort of sleep you're probably doing something wrong – null Feb 18 '16 at 12:32
  • 2
    *"I know i am not doing anything wrong but the output shows otherwise"* - In other words you *are* doing something wrong? Can you explain in more detail why you think you need a delay? – nnnnnn Feb 18 '16 at 12:33
  • @Rory i am comparing images in the function in settimeout clause and passing image name to compare. – soCalledDeveloper Feb 18 '16 at 12:36
  • @nnnnnn i need delay because the function need some time to compare image if i won't use delay it will directly shows up that last value . – soCalledDeveloper Feb 18 '16 at 12:37
  • Please read about [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and ask a new question... – A. Wolff Feb 18 '16 at 12:38
  • that worked for me [JavaScript : For loop with timeout](http://stackoverflow.com/questions/24293376/javascript-for-loop-with-timeout) too – soCalledDeveloper Feb 18 '16 at 12:55

0 Answers0