Skip to content

Instantly share code, notes, and snippets.

@A
Created January 20, 2014 11:44
Show Gist options
  • Save A/8518725 to your computer and use it in GitHub Desktop.
Save A/8518725 to your computer and use it in GitHub Desktop.
// 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