Created
January 15, 2018 12:23
-
-
Save marcoala/e7c379de2823ae6b0da961087670bc13 to your computer and use it in GitHub Desktop.
Demonstration of how setTimeout and multi-thread work in JS. Read the comment for more details.
This file contains hidden or 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
| // original reference https://davidwalsh.name/es6-generators | |
| /** | |
| * This function create a timeout that should be executed after 1 millisecond | |
| */ | |
| function timeoutFunction() { | |
| setTimeout(function() { | |
| console.log('Timeout'); | |
| }, 1); | |
| } | |
| /** | |
| * This function create a a loop that takes more than 1 millisecond to be | |
| * executed | |
| */ | |
| function loopFunction() { | |
| for (var i = 0; i < 1000; i++) { | |
| console.log('Loop'); | |
| } | |
| } | |
| /** | |
| * This Self-Invoking function make sure that the two previous function are | |
| * called one right after the other | |
| */ | |
| (function() { | |
| timeoutFunction(); | |
| loopFunction(); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First, we create a timeout at 1 millisecond, then we execute a function that lasts longer than 1 millisecond.
In a multi-thread environment we will expect to see in the console the output of the timeout exactly after 1 millisecond, but javascript is single-threaded so we need to wait until the second function is over before executing the timeout function.
So
setTimeoutshouldn't be read as "Execute this function after X millisecond" but as "Wait X millisecond, and then at the first available time execute this function".