From 95abb75c7a040c8d91bc27b617a933b3e55b8b54 Mon Sep 17 00:00:00 2001 From: Deep Kothari Date: Fri, 21 Jun 2024 22:57:08 +0530 Subject: [PATCH] Ep-17 | TRUST ISSUES with setTimeOut() --- Namaste-JavaScript/Ep-16-JS-Engine-V8.js | 14 ++++++ .../Ep-17-SetTimeOut-Trust-Issues.js | 43 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 Namaste-JavaScript/Ep-16-JS-Engine-V8.js create mode 100644 Namaste-JavaScript/Ep-17-SetTimeOut-Trust-Issues.js diff --git a/Namaste-JavaScript/Ep-16-JS-Engine-V8.js b/Namaste-JavaScript/Ep-16-JS-Engine-V8.js new file mode 100644 index 0000000..2352b7c --- /dev/null +++ b/Namaste-JavaScript/Ep-16-JS-Engine-V8.js @@ -0,0 +1,14 @@ +// JS runs literally everywhere from smart watch to robots to browsers because of Javascript Runtime Environment JRE. +// Itʼs all because of Javascript runtime Environment JRE + +// JRE container has All the things required to runs javascript code. +// JRE is not possible without +// Js Engine Heart of JRE + +// JS creator Brendan Eich), v8 Chrome + + +// Code inside Javascript Engine passes through 3 steps: +// 1. Parsing +// 2. Compilation +// 3. Execution diff --git a/Namaste-JavaScript/Ep-17-SetTimeOut-Trust-Issues.js b/Namaste-JavaScript/Ep-17-SetTimeOut-Trust-Issues.js new file mode 100644 index 0000000..2fd7d1c --- /dev/null +++ b/Namaste-JavaScript/Ep-17-SetTimeOut-Trust-Issues.js @@ -0,0 +1,43 @@ +function cb () { + console.log("Callback"); +} + +setTimeout(cb,5000); // Does'nt take exactly 5000 ms but it guarantees that it takes atleast 5000 ms And maybe Anytime after that... + +// Comment clarified: +// setTimeout does not guarantee that the callback method will be called exactly after 5 seconds. +// It might take slightly longer if the call stack is busy. + +console.log("Start"); +setTimeout(function cb () { + console.log("Callback"); +},5000); +console.log("End"); + +let startDate = new Date().getTime(); +let endDate = startDate; +while (endDate < startDate + 10000) +{ + endDate = new Date().getTime(); +} +console.log("while expires"); + + +// Why JS has only one callsatck ? +// Synchronous single threaded language +// it has just 1 main thread and 1 call satck +// all the pieces of code executed there inside +// it makes interpreted language and it runs very fast even inside browser + +// you dont have to wait for compiled just like languages +// it hase just in time compilation + +// we can still do asynchronous operations + + +setTimeout(function deep () { + console.log("-------- Less Important... it Might be on 4th page or not at priority --------"); +},0) + +// In short Defer some piece of code +// After completed execution of whole thread it goes into callback queue and then callstack run that function \ No newline at end of file