Function call inside a $.each loop, is it async or sync?
Asked Answered
M

3

10

Assume a simple for-each loop ($.each), where for-each iteration I call a function set in the global scope. Does the function run synchronously or asynchronously? Assume no Ajax, so what the function does is completely synchronous, albeit merely executed. In other words, I wonder whether the function call itself is blocking within the iteration or not.

Thanks!

Marileemarilin answered 23/7, 2015 at 23:48 Comment(0)
P
5

Everything in JavaScript is synchronous. If you're not using timeouts or callbacks everything will be "synchronous".

Simple example should prove it.

var data = [1,2,3];
var results = [];
$.each(data, function(d) { results.push(d); });

console.log(results); // [1,2,3]
Plantation answered 23/7, 2015 at 23:55 Comment(1)
So you guys are saying the iteration will not continue until the function called is done running, correct?Marileemarilin
H
6

It is synchronous. You can tell if you set a breakpoint after the loop and one inside the loop. The breakpoint in the loop will be hit before the one after the loop.

This is assuming the breakpoints will be hit in the execution, object/array being looped over has items, etc.

Hydrops answered 23/7, 2015 at 23:52 Comment(0)
P
5

Everything in JavaScript is synchronous. If you're not using timeouts or callbacks everything will be "synchronous".

Simple example should prove it.

var data = [1,2,3];
var results = [];
$.each(data, function(d) { results.push(d); });

console.log(results); // [1,2,3]
Plantation answered 23/7, 2015 at 23:55 Comment(1)
So you guys are saying the iteration will not continue until the function called is done running, correct?Marileemarilin
C
1

It's synchronous. You can see the source code here, there's no a synchronous programming involved.

http://www.james.padolsey.com/jquery/#v=1.11.2&fn=jQuery.each

Carminecarmita answered 23/7, 2015 at 23:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.