Explore the implementation of setTimeout in JavaScript with a detailed explanation for every step. Understand all scenarios expected to implement the setTimeout polyfill.
Anuj Sharma
Last Updated Aug 3, 2025
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
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.
Here is the implementation code of the setTimeout polyfill in JavaScript
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);
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
Timer ID generation
timerId gets generated using Math.random().Recording the start time
Date.now(), it store the time when mySetTimeout is called.Checking the delay
check() which compares the current time with the start time.requestAnimationFrame(check).Returning the timer ID
timerId, this ID can be used to clear the timeout using clearTimeout function.❇️ 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
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 🚀
Be the first to share your thoughts!
No comments yet.
Start the conversation!
Build Your Portfolio
Help the Community
Strengthen Your Skills
Share your knowledge by writing a blog or quick notes. Your contribution can help thousands of frontend developers ace their interviews and grow their careers! 🚀
Anuj Sharma
Last Updated Nov 23, 2025
Explore code explanation of useToggle() custom hook in react to handle the toggle event efficiently.
Anuj Sharma
Last Updated Nov 24, 2025
Understand step by step how to flatten nested array in javascript using recursion, also explore the flatten of complex array of object.
Anuj Sharma
Last Updated Nov 23, 2025
Find the step-by-step explanation of the useFetch custom hook in React that helps in fetching the data from an API and handling loading, error states.
Alok Kumar Giri
Last Updated Jun 2, 2025
Code snippet examples which will help to grasp the concept of Hoisting in JavaScript, with solutions to understand how it works behind the scene.
Anuj Sharma
Last Updated Nov 23, 2025
Implement useThrottle Custom Hook In React (Interview) to limit the number of APi calls to improve the performance of application.
Anuj Sharma
Last Updated Oct 2, 2025
Explore Polyfill for map, filter and reduce array methods in JavaScript. A detailed explanation of Map, filter and reduce polyfills in JS helps you to know the internal working of these array methods.
Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.
© 2025 FrontendGeek. All rights reserved