Skip to content

Instantly share code, notes, and snippets.

@andrelandgraf
Last active July 29, 2018 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrelandgraf/28770cace5fa1507611eff4cf1168b39 to your computer and use it in GitHub Desktop.
Save andrelandgraf/28770cace5fa1507611eff4cf1168b39 to your computer and use it in GitHub Desktop.
working with the js event loop
// timeouts are handy to fake async calls
// setTimeout(callback function, 1500 /*milliseconds*/, 'parameters');
function doSomething(name, callback){
// 2.) task 1: we execute console.log('1');
console.log('1');
// 3.) task 1: we execute setTimeout. Set timeout creates a new task (task 2) that will be executed in 1500 milliseconds from now on
setTimeout(callback, 1500, name);
// 4.) task 1: we execute console.log('2');
console.log('2');
}
// 1.) task1: Execution starts here in the global scope, calling the function doSomething
doSomething('Alice', function(message){
// task: 2 starts always after taks1 and only after 1500 milliseconds and executes console.log('Alice');
console.log(message);
});
/* => Output:
* 1
* 2
* Alice
*
* Answer: The event loop handles one code task after another
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment