Skip to content

Instantly share code, notes, and snippets.

@marcoala
Created January 15, 2018 12:23
Show Gist options
  • Select an option

  • Save marcoala/e7c379de2823ae6b0da961087670bc13 to your computer and use it in GitHub Desktop.

Select an option

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.
// 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();
})();
@marcoala
Copy link
Author

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 setTimeout shouldn'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".

@kemalgenc
Copy link

thanks for explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment