|
| 1 | +# Episode 17 : Trust Issues with setTimeout() |
| 2 | + |
| 3 | +(Episode number mixup. This is the actual 17th episode) |
| 4 | + |
| 5 | +``` |
| 6 | +console.log("Start"); |
| 7 | +
|
| 8 | +setTimeout(function cb() { |
| 9 | + console.log("Callback"); |
| 10 | + }, 5000); |
| 11 | + |
| 12 | + console.log("End"); |
| 13 | + |
| 14 | +setTimeout sometimes does not exactly guarantee that the callback method will be called exactly after 5s. |
| 15 | +Maybe 6,7 or even 10! It all depends on callstack |
| 16 | +``` |
| 17 | + |
| 18 | +While execution of program |
| 19 | + |
| 20 | +- First GEC is created and pushed in callstack. |
| 21 | +- Start is printed in console |
| 22 | +- When setT is seen, callback method is registered into webapi's env. And timer is attached to it and started. cb waits for its turn to be execeuted once timer expires. |
| 23 | +But JS waits for none. Goes to next line |
| 24 | +- End is printed in console. |
| 25 | +- After "End" suppose we have 1 million lines of code that runs for 10 sec(say). So GEC won't pop out of stack. It runs all the code for 10 sec. |
| 26 | +- But in the background, the timer runs for 5s. While callstack runs the 1M line of code, this timer has already expired and cb fun has been pushed to Callback queue. |
| 27 | +- Event loop keeps checking if callstack is empty or not. But here GEC is still in stack so cb can't be popped from callback Q and pushed to CallStack. |
| 28 | +** Though setT is only for 5s, it waits for 10s until callstack is empty before it can execute**(When GEC popped after 10sec, cb() is pushed into call stack and |
| 29 | +**immediately executed** (Whatever is pushed to callstack is executed instantly) |
| 30 | +- This is called as the **Concurrency model of JS**. This is the logic behind setT's trust issues |
| 31 | + |
| 32 | +### The First rule of JavaScript |
| 33 | +- **Do not block the main thread** (as JS is a single threaded(only 1 callstack) language) |
| 34 | + |
| 35 | +- This raises a question. *Why not add more call stacks and make it multithreaded?* |
| 36 | +- JS is a synch single threaded language. And thats its beauty. With just 1 thread it runs all pieces of code there. It becomes kind of an interpreter lang, |
| 37 | +and runs code very fast inside browser (no need to wait for code to be compiled) |
| 38 | + |
0 commit comments