0

Since I'm not very experienced with regard to Javascript, I'm kinda baffled about the function order.

In the following example I'd expect console.log() to be processed AFTER wait() is finished.

function wait() {
    setTimeout(function () {
        console.log("wait " + new Date().getTime());
    }, 3000);
}

wait();

console.log("global " + new Date().getTime());

The console shows those values:

global 1499993535591 wait 1499993538592

Why is the second function being processed before the first one isn't even completed?

This is causing me some problems when I fill an array inside a function and need to do something with it outside of that function, because it's still empty then.

Braunbaer
  • 1
  • 3
  • 2
    setTimeout is non-blocking – Hamms Jul 14 '17 at 00:02
  • 3
    asynchronous code can be tricky https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Jaromanda X Jul 14 '17 at 00:02
  • 3
    JavaScript is single-threaded. Nothing ever happens simultaneously. Asynchronous functions have to wait for the main thread to finish before they're eligible to run. Even if the delay was `0` on your `setTimeout`, the execution order would still be the same. – 4castle Jul 14 '17 at 00:05
  • See https://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron?newsletter=1&nlcode=97716%7c4ba7 about filling a variable inside an asynchronous function. – Barmar Jul 14 '17 at 00:09
  • Thanks for the quick help. Much appreciated. – Braunbaer Jul 14 '17 at 00:18

2 Answers2

0

setTimeout is async, it doesn't wait before executing the next line but instead will execute the code when the delay you've set is done.

T4rk1n
  • 1,380
  • 12
  • 15
0

setTimeout is non-blocking - whatever you do, don't just "use async: false", unless you want the user experience to involve just "freezing up" while they wait. Instead learn how to work with async patterns (link credit SLaks)

Julix
  • 598
  • 1
  • 9
  • 20