📘
snesjhon
  • You Should Know
  • Personal
    • Blogs
      • I'll never complain about web tooling again.
      • vscodevim
  • JavaScript
    • Closures
      • Closure Q1
    • Values
      • Primitive vs Reference
      • Accessing by value and reference
    • Function
      • call, apply, bind
      • Pass by value
      • Different types of Scopes
      • Context vs Scope
      • Parse Time Vs Run Time
    • Hosting
      • Are Let & Const Hoisted?
      • Hoisting Q1
      • Hoisting Q2
    • Standard Objects
      • Math
        • Math.log10
        • Math.pow()
    • Array
      • Apply
      • Slice vs Splice vs Split
    • This
      • This - Q1
    • TypeScript
      • as const
    • FAQs
      • Modulo Operator
      • Timeout
      • Declarative vs Imperative
      • ++i vs. i++
    • Interview Questions
  • react
    • FAQs
  • Ruby
    • Debugging
    • Symbols
    • Intro
  • Algorithms
    • Sliding Window
      • minSubArrayLen
      • maxSubArraySum
      • findLongestSubstring
    • Frequency Counter
      • sameFrequency
    • Recursion
      • nestedEvenSum
      • flatten
      • Reverse a String
      • Fibonnacci
    • Searching
      • overlappingIntervals
      • twoStringSearch
      • binarySearch
    • Sort - Elementary
      • Selection Sort
      • Bubble Sort
      • Insertion Sort
      • quickSort
    • Sort - Intermediate
      • Radix Sort
      • Merge Sort
    • FAQs
  • Data Structures
    • Breadth First Search
    • Linked Lists
      • Singly Linked Lists
    • FAQs
  • Code Challenges
    • LeetCode
      • removeDuplicates
    • Hacker Rank
      • twoSums
      • Sock Merchant
    • Hacker Rank - Medium
      • New Year Chaos
  • Databases
    • SQL
Powered by GitBook
On this page
  • What would the input be?
  • Resources
  1. JavaScript
  2. FAQs

Timeout

setTimeout adds the callback into the loop, in order that it was added. But you should also take into account that there can be some time between what you added and what you fired.

console.log("a");

const time1 = setTimeout(() => {
  console.log("b");
}, 1);

const time2 = setTimeout(() => {
  console.log("c");
}, 10);

const time3 = setTimeout(() => {
  console.log("d");
}, 0);

console.log("e");

What would the input be?

Initially I thought it'd be a,e,d,b,c but that's wrong because I was thinking that because the the setTimeout would take into account delay that it'd place the d before the b. However because the time that it takes for the a,e to print out is theoretically a millisecond that it'd might as well be the same time as 0. It's just that because in the eventloop the b was placed before the c then it would fire first.

Answer: a,e,b,d,c

Resources

Last updated 4 years ago

https://www.youtube.com/watch?v=USbiLiF9NDY&t=194s