Async function (delayed execution on event loop)
by JThomas
JavaScript
function sync_Execute() {
console.log("I'm executing synchronously...");
console.log(exe('1'));
console.log('I will come after 1...');
}
function async_Execute() {
console.log("I'm executing asynchronously...");
exe('1', function (m) {
console.log(m);
});
console.log('I normally should come after 1, but could be before it.');
}
function exe(msg, cb) {
var fn = function () {
for (var i = 0; i < 1000000000; i++) {
var b = i % 5;
}
};
//Async execution
if (cb) {
setTimeout(function () {
fn();
cb(msg);
}, 0);
}
fn();
//synchronous execution
return msg;
}
sync_Execute();
async_Execute();