Skip to content

Instantly share code, notes, and snippets.

@andrelandgraf
Created July 29, 2018 15:44
Show Gist options
  • Select an option

  • Save andrelandgraf/a7bf8b8c00b6e20cd8974d50c980f661 to your computer and use it in GitHub Desktop.

Select an option

Save andrelandgraf/a7bf8b8c00b6e20cd8974d50c980f661 to your computer and use it in GitHub Desktop.

Revisions

  1. andrelandgraf created this gist Jul 29, 2018.
    26 changes: 26 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    /*
    * what happens if task 1 takes longer than 1500 milliseconds to be executed? Does task 2 has to wait?
    */
    function doSomethingLonger(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');
    while(true);
    console.log('2');
    }

    // 1.) task1: Execution starts here in the global scope, calling the function doSomething
    doSomethingLonger('Alice', function(message){
    // task: 2 starts after 1500 milliseconds and executes console.log('Alice');
    console.log(message);
    throw new Error('For gods sake, stop this madness and break the loop');
    });

    /* => Output:
    * 1
    * pending...
    *
    * The event loop handles one task after another, task 2 will never start, and console.log('2'); is unreachable as well.
    */