Created
January 20, 2014 11:44
-
-
Save A/8518725 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Synchronous | |
var a = function (x) { | |
while(new Date().getTime() < now + 1000) { | |
// do nothing | |
} | |
console.log(x) | |
}; | |
a(1); // waits 1 sec and prints 1 | |
a(2); // waits for finish `a(1)` then wait another 1 sec and prints 1 | |
a(3); // waits for finish `a(1)` and `a(1)` then wait another 1 sec and prints 1 | |
// Synchronous | |
var b = function (cb) { | |
var start = new Date().getTime(); | |
while(new Date().getTime() < start + 1000) { | |
// do nothing | |
} | |
cb(); | |
}; | |
b(function(){console.log(1)}); // waits 1 sec and prints 1 | |
b(function(){console.log(2)}); // waits for finish `b(function(){console.log(1)});` then wait another 1 sec and prints 1 | |
b(function(){console.log(3)}); // waits for finish `b(function(){console.log(2)});` and `b(function(){console.log(3)});` then wait another 1 sec and prints 1 | |
// Asynchronous | |
var c = function (cb) { | |
var start = new Date().getTime(); | |
setTimeout(function () { | |
while(new Date().getTime() < start + 1000) { | |
// do nothing | |
} | |
cb(); | |
}, 0); | |
}; | |
c(function(){console.log(1)}); // Init setTimeout's callback and release JS runtime. | |
c(function(){console.log(2)}); // Init setTimeout's callback and release JS runtime. | |
c(function(){console.log(3)}); // Init setTimeout's callback and release JS runtime. | |
// log 1,2,3 at same time. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment