View difference between Paste ID: VGa02dRw and kQkdLJ9y
SHOW: | | - or go back to the newest paste.
1
var test;
2
3
// Synchronous
4
test = 'before';
5
6
// Asynchronous
7
var myFunction = function (cb) {
8
    // Let's pretend this is network or filesystem access...
9
    setTimeout(function () {
10
        cb('after')
11
    }, 1000);
12
}
13
myFunction(function(result) {
14
   test = result;
15
});
16-
     
16+
17-
console.log(test); // Outputs 'before', because myFunction has not yet called the callback
17+
// This executes out of order, because setTimeout is async     
18-
setTimeout(function () {
18+
setTimeout(function () { 
19-
    console.log(test); // Outputs 'after', because myFunction has eventually called the callback
19+
    console.log(test); 
20-
}, 2000);
20+
}, 2000);
21
console.log(test);
22
23
// Output:
24
// > before
25
// > after