Blog/NotesConcept

setTimeout Polyfill in JavaScript - Detailed Explanation

Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.

Intermediate

Anuj Sharma

Last Updated Jun 15, 2026


setTimeout Polyfill in JavaScript - Detailed Explanation

setTimeout in JavaScript is a very commonly used function to add a delay in the execution of a callback function, and understanding the internal workings of setTimeout gives a solid understanding of asynchronous JavaScript.

In this post, we will learn how to implement a simple polyfill for setTimeout using JavaScript

Table of Contents

Expected scenarios for setTimeout polyfill in JavaScript

Let’s go through what all the expected scenario needs to be fulfilled by the custom setTimeout function in JavaScript:

✅ It should take a callback function to execute later.

✅ It should accept a delay time (in milliseconds) after which the callback should run.

✅ It should optionally accept arguments to pass to the callback.

✅ It returns a timer ID that can be used to clear the timeout using clearTimeout.

Implementation of setTimeout polyfill in JavaScript

Here is the implementation code of the setTimeout polyfill in JavaScript 

setTimeout polyfill code with example

In this polyfill implementation code, requestAnimationFrame is used to mimic the delay loop, since we are not allowed to use setTimeout itself.

🚀 Check out the live code - setTimeout in JavaScript

function mySetTimeout(callback, delay, ...args) {
   // Validate input arguments
   if (typeof(callback) != 'function') throw new Error("callback should be a function");
   if (typeof(delay) != 'number' || delay < 0) throw new Error("delay should be a positive number");

  // Generate a unique ID for this timeout
  const timerId = Math.random().toString(36).substring(2);

  // Record the start time
  const start = Date.now();

  // Create a function that checks if enough time has passed
  function check() {
    const current = Date.now();
    if (current - start >= delay) {
      callback(...args); // Call the callback with provided arguments
    } else {
      // Keep checking until delay is reached
      requestAnimationFrame(check);
    }
  }

  // Start checking
  requestAnimationFrame(check);

  // Return an timeId that can be used for clearInterval
  return timerId;
}

// Example usage
mySetTimeout(() => {
  console.log("Greet hello after 2 seconds");
}, 2000);

Explanation of the setTimeout polyfill

Here is the step-by-step explanation of the setTimeout polyfill Implementation

Function signature

In the code mySetTimeout function accepts below arguments, similar to the setTimeout implementation in JavaScript

  • callback → the function to run later.
  • delay → how long to wait (in milliseconds).
  • ...args → optional arguments to pass to the callback when it runs.

Validate Input Arguments

  • Validate callback function type and the delay to ensure the function input is valid.

Timer ID generation

  • In this step a random timerId gets generated using Math.random().
  • This helps in uniquely identifying each timeout instance that will be returned from the function and can be used later in clearTimeout

Recording the start time

  • Using Date.now(), it store the time when mySetTimeout is called.

Checking the delay

  • We define a function check() which compares the current time with the start time.
  • If the required delay has passed, we execute the callback with any arguments provided.
  • If not, we schedule another check using requestAnimationFrame(check).

Returning the timer ID

  • Finally, we return the timerId, this ID can be used to clear the timeout using clearTimeout function.

What's Next

❇️ Check out clearTimeout polyfill in JavaScript

❇️ Check out clearInterval polyfill in JavaScript

❇️ Check out setInterval polyfill in JavaScript

❇️ Find Best resources to prepare for Polyfills in JavaScript

Love this Blog? Share it Now!

Help others discover this resource

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀


Learn Next

Featured

Promise Polyfill in JavaScript - Step by Step Explanation

setInterval polyfill in JavaScriptPromise.any Polyfill in JavaScriptPromise.all Polyfill in JavaScriptPromise.race Polyfill in Javascript

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀

Share your expertise

Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.

Build your portfolio

Help the community

Sharpen your skills

Earn goodies

Other Related Blogs

clearTimeout polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Jun 15, 2026

Understand the implementation of the clearTimeout polyfill in JavaScript with a detailed explanation of each and every step.

Promise.race Polyfill in Javascript - Detailed Explanation

Anuj Sharma

Last Updated Jun 15, 2026

Detailed step-by-step explanation of Promise.race polyfill in javascript to understand its internal working and handling of race conditions among promises.

setInterval polyfill in JavaScript - Detailed Explanation

Anuj Sharma

Last Updated Jun 15, 2026

Understand the implementation of the setInterval polyfill in JavaScript with a detailed explanation of each and every step.

Promise Polyfill in JavaScript - Step by Step Explanation

Anuj Sharma

Last Updated Jun 15, 2026

An Interview-focused explanation of Promise Polyfill in JavaScript which helps to understand both Functional and ES6 custom promise implementation.

Promise.all Polyfill in JavaScript - Detailed Explanation [For Interviews]

Anuj Sharma

Last Updated Jun 5, 2026

Deep dive into promise.all polyfill in javascript will help to understand the working of parallel promise calls using Promise.all and its implementation to handle parallel async API calls.

Polyfill for Async Await in JavaScript - Step by Step Explanation

Anuj Sharma

Last Updated Feb 21, 2026

Understand polyfill for Async Await in JavaScript with a step-by-step explanation. This helps in understanding the internal functioning of Async Await in JavaScript.

Promise.any Polyfill in JavaScript - Detailed Explanation

Frontendgeek

Last Updated Sep 18, 2025

A step-by-step detailed explanation of Promise.any polyfill in JavaScript to understand the internal implementation to handle race conditions among promises to result in a single resolved promise.

Promise.allSettled Polyfill in JavaScript - Step by Step Explanation

Frontendgeek

Last Updated Sep 18, 2025

Deep dive into Promise.allSettled Polyfill in JavaScript, which helps to understand the internal implementation of Promise.allSettled method to handle parallel calls with failure cases.

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

All in One Preparation Hub to Ace Frontend Interviews. Master JavaScript, React, System Design, and more with curated resources.

Consider Supporting this Free Platform

Buy Me a Coffee

Product

HomeFrontend InterviewFrontend JobsQuestionsNewInterview ExperienceBlogsToolsLeaderboardFrontendGeek Chrome extensionGet the extension on the Chrome Web Store

© 2026 FrontendGeek. All rights reserved