Understanding JavaScript setTimeout Function Asynchronous Time-Based Execution
Table of contents
- Introduction
- What is setTimeout
- Syntax of setTimeout
- Parameters
- How setTimeout Works
- Understanding the Event Loop and Asynchronous Code Execution
- Adding the Callback to the Message Queue after the Specified Delay
- Execution of the callback when the call stack is empty
- Clearing a Timeout
- Syntax of ClearTimeOut
- Parameter
- The Common Problems with setTimeOut
- Best Practices for setTimeout
- async await
- Syntax
- Comparing setTimeout with setInterval
- Conclusion
Introduction
Asynchronous from Greek asyn-, meaning "not with," and Chronos, meaning "time" is an adjective describing objects or events that are not coordinated in time. So, when something is asynchronous, tasks or actions can happen at different times, and they don't have to wait for each other. It's like having a playtime that never stops, everyone can have fun doing different things simultaneously.
An Asynchronous code means the computer won't wait for a line to finish before going to the next line, Instead, it allows multiple tasks to be initiated and run independently of each other.
An Asynchronous operates Certain programming languages, like C#, Javascript, and Python. It supports the method of non-blocking code. Asynchronous code functions by placing events in a queue and processing them one by one with the corresponding event handler. Most of the code in a scene runs synchronously using a single thread.
SetTimeOut() is a built-in function in JavaScript that allows you to schedule the execution of a callback function after a specified delay.
What is setTimeout
SetTimeOut allows us to run Function in the future. setTimeOut
takes two parameters, the first parameter is a function that we want to run in the future while the second parameter is how long to wait before running the first parameter
Syntax of setTimeout
setTimeOut(callback, Delay, param1, param2, ...)
Parameters
a parameter is a special type of information that you can give to a function or a process. It's like providing specific instructions or details to tell the function what to do or how to perform a certain task. Parameters help customize the behavior of a function and allow it to work with different values or data, making the function more flexible and useful in various situations. Think of parameters as the input that you can give to a function so that it can work with that input and give you the desired output.
The
callback
a function to be executed after the timer expires. Is like a special instruction that tells the computer what to do after waiting for a specific amount of time.The
delay
is the time the computer has to wait before following that instruction. It's like setting a (it's optional) timer before doing something. The time is inmilliseconds,
the number of milliseconds,1000 milliseconds is equal to one second
and so on etc.param1
,param2
You can also give extra pieces of information (param1, param2,) along with the instruction if you want the computer to use that information while doing the task. It's like giving additional details for the computer to consider. it's also optional.
setTimeout(function() {
console.log('timeOut');
}, 3000);
//output
// time > After 3 seconds
How setTimeout Works
setTimeout
is a function in JavaScript that enables asynchronous code execution, You tell JavaScript to wait for a certain time (the delay
) before doing something. It's useful when you want to schedule a task to happen later, not immediately. To understand how setTimeout
works, let's break down the process step by step.
Understanding the Event Loop and Asynchronous Code Execution
In JavaScript, there's a special loop called the "event loop." The event loop keeps checking if there are any tasks to be done in a "to-do list." If there's a task in the list, the event loop takes it and starts doing it. Some tasks take a long time to finish, but the event loop doesn't want to stop everything else from happening, so it keeps checking for new tasks while the old ones are still going on.
setTimeout(function() {
console.log("watch Netflix");
}, 6000);
setTimeout(function() {
console.log("Do the laundry");
}, 4000);
setTimeout(function() {
console.log("Make Dinner");
}, 1000);
//output
//Make Dinner > immediately
//Do the Laundry > After 4 seconds
//Watch Netflix > After 6 seconds
The third
function is called immediately and executes without any delay.
Notice how both first
and second
functions are scheduled to run after their respective delays using setTimeout
. Even though the first
function is called first, it waits for 6 seconds before executing, during which the second
function gets a 4 seconds delay and is executed earlier. After the delays, the second
function executes, followed by the first
function when its 6 seconds timer finally completes.
Adding the Callback to the Message Queue after the Specified Delay
When you use setTimeout
, you add a task (the callback) to the "to-do list" after a certain time (the delay) has passed. The task stays in the list, waiting for its turn.
function greet() {
console.log("Hello! Welcome to our channel.");
}
function showPopup() {
console.log("Please subscribe to my youtube channel!");
}
setTimeout(greet, 2000);
setTimeout(showPopup, 3000);
console.log("Greetings and popup scheduled.");
//output
// Greet > Hello! Welcome to our channel //After 2 seconds
//showPopup > Please subscribe to my youtube channel //After 3 seconds
We have two functions, greet
and showPopup
, which was executed after specific delays. Using setTimeout
, we set the greet
function to be executed after 2 seconds and the showPopup
function to be executed after 3 seconds. The program continues with the next line of code without waiting for the delays. After the specified delays, the functions are added to the message queue. Once the call stack is empty, the event loop picks the functions from the message queue and executes them.
Execution of the callback when the call stack is empty
Execution of the callback, when the call stack is empty, is an important part of how asynchronous
JavaScript handles tasks that don't happen all at once. Synchronous code on the other hand will wait for one line to finish before going to the next line.
setTimeout(function() {
console.log('toDoList 1: Make Dinner');
}, 3000);
// Make Dinner //after 3 seconds
SetTimeOut is asynchronous code that waits a certain period before executing the callback however synchronous doesn't wait for three seconds to finish, it set up the timer and immediately executes, I'm going to add another toToList: Do Laundry
setTimeout(function() {
console.log('toDoList 1: Make Dinner');
}, 3000);
console.log('toDoList 2: Do Laundry')
//output
//Do Laundry //Immediately
//Make Dinner //After 3 seconds
synchronous code simply means the Computer will wait for one line to finish before going to the next line.
The code inside the function is synchronous code, if I add another code inside the function ('todo-list 1: Do the Dishes'
) and save. The codes inside the function will still run line by line. It will wait for each line to finish before displaying the next line, and after four seconds it will display the string on the console.
setTimeout(function() {
console.log('toDoList 2: Make Dinner');
console.log('toDoList 3: Do the Dishes');
}, 4000);
console.log('toDoList 1: Do Laundry');
//output
//Do Laundry
// Make Dinner
//Do the dishes
The only time a code becomes Asynchronous is when we use certain features of JavaScript like setTimeOut, so setTimeOut is the only part that is Asynchronous.
Clearing a Timeout
clearTimeout is a JavaScript function used to cancel a task execution of a function that was previously set using setTimeout. It's like having to turn off an alarm on your phone before it goes off, so you can change your mind and avoid the function from happening.
Syntax of ClearTimeOut
clearTimeout(timeoutId);
Parameter
- timeOutID
The identifier of the timeOut you want to cancel. This ID was returned by the corresponding call to.
We are going to make use of our previous code on todo-list
by canceling our Make Dinner and Do the Dishes todo-list
We will start by defining a variable to store the timeOut ID and then set the function with setTimeOut and store the ID in the variable.
// Define the variable
let timeoutId;
// storing the ID in the Variable
timeoutId = setTimeout(function() {
console.log('toDoList 1: Make Dinner');
console.log('toDoList 2: Do the dishes');
}, 4000);
clearTimeout(timeoutId);
console.log('Do Laundry');
//ouput Do laundry
In this code, you will notice the codes in the function did not execute, we declare a variable timeoutId
to store the timeout ID returned by setTimeout
. Then, we set the function to execute after four seconds and store the timeout ID in the timeoutId
variable. Immediately after setting the timeout, we use clearTimeout(timeoutId)
to cancel the scheduled function, so the todo-list
messages will not be displayed in the console. Instead, only the "Do Laundry" message will be displayed.
The Common Problems with setTimeOut
setTimeout
can be powerful, but there are some potential pitfalls to be aware of, especially when dealing with long delays.
Inaccurate Timing: The timing of
setTimeout
might not be exact due to other tasks or events in the browser, causing delays to vary.Accumulated Delays: Repeatedly using
setTimeout
with long delays can lead to unexpected behavior, as delays may stack up.Callback Stack Overflow: Recursive functions inside
setTimeout
can cause a stack overflow if not handled properly.
Best Practices for setTimeout
Avoid Long Delays: For precise timing or long delays, consider alternative methods like Web Animations API.
Clear Timers Properly: Always use
clearTimeout
to cancel scheduled timeouts.Be Mindful of Short Delays: Rapid function calls with short delays may lead to performance issues.
Handle Errors: Wrap
setTimeout
calls in try-catch blocks to manage errors effectively.Consider Promises or Async/Await: Use Promises or async/await for complex asynchronous operations.
Test and Debug: Thoroughly test and use debugging tools to check
setTimeout
behavior.
Further explain with our previous code.
setTimeout(function() {
console.log('toDoList 1: Make Dinner');
console.log('toDoList 2: Do the dishes');
}, 4000);
console.log('Do Laundry');
Issue: The code uses setTimeout
to set the output of "Make Dinner" and "Do the dishes" after 4 seconds. However, there's no guarantee that the timeout will be precisely 4 seconds. Other tasks or events in the browser might cause the actual delay to vary.
Explanation: When you run this code, the setTimeout
function schedules the function provided (with the "Make Dinner" and "Do the dishes" messages) to be executed after waiting for 4 seconds. However, JavaScript continues executing the code without waiting for the timeout to finish. As a result, the "Do Laundry" message is logged immediately.
Potential Pitfall: The actual delay before the messages are logged might vary. If the JavaScript thread is busy with other tasks, the delay can be longer than 4 seconds, leading to unexpected timing in your application.
Best Practice: If precise timing is essential for your application, consider using alternative methods like Promises or async/await
. Promises can provide better control over asynchronous tasks and help ensure predictable execution times.
I will briefly explain ansync/await
async await
async/await
is a way to write asynchronous code in JavaScript that makes it look and behave more like synchronous code. It helps make your code easier to read and understand, especially when dealing with tasks that take time, like fetching data from a server or waiting for a timer.
Syntax
async
keyword: It is used before a function declaration or expression. It tells JavaScript that the function contains asynchronous operations and will return a Promise implicitly.await
keyword: It can only be used inside anasync
function. It pauses the execution of the function until the Promise is resolved (i.e., until the asynchronous task is completed)
Again, let's use the todo list example to understand async/await
// Function to simulate a delay using a Promise
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Async function to handle the todo list
async function main() {
// First task
console.log('Do Laundry');
// Wait for 4 seconds before proceeding to the next task
await delay(4000);
// Second task
console.log('toDoList 1: Make Dinner');
console.log('toDoList 2: Do the dishes');
}
// Call the main function
main();
//output
//Do Laundry
//after 4 seconds delay
//toDoList 1: Make Dinner
//toDoList 2: Do the dishes
async function main()
: This defines an async
function called main
. It means this function will deal with asynchronous tasks. However, await delay(4000)
The await
keyword is used to wait for the delay
function to complete. The delay
function returns a Promise that resolves after 4 seconds (4000
milliseconds). While waiting, the function will pause here, but other parts of your code can continue executing.
Comparing setTimeout with setInterval
Differences between setTimeout and setInterval
Timing:
setTimeout
: Executes the specified function once after a specified delay (in milliseconds).setInterval
: Repeatedly executes the specified function with a fixed time interval between each execution (in milliseconds).
Number of Executions:
setTimeout
: Executes the function only once.setInterval
: Executes the function repeatedly at regular intervals until it is explicitly stopped usingclearInterval
.
When to Use
Use
setTimeout
for single delayed tasks, like displaying a message after a delay.Use
setInterval
for tasks that need to happen repeatedly, like updating a clock or creating animations.
Code example of using setInterval()
function TodoList() {
console.log('toDoList 1: Make Dinner');
console.log('toDoList 2: Do the dishes');
}
console.log('Do Laundry');
// Call printTodoList every 4 seconds
const intervalId = setInterval(TodoList, 4000);
We have a function called printTodoList
that logs the todo-list
items "Make Dinner" and "Do the dishes" to the console. We start by logging "Do Laundry" to the console immediately. Then, we use setInterval
to call the printTodoList
function repeatedly at a fixed interval of 4 seconds (4000 milliseconds).
This will be the output ๐of the setInterval(), repeatedly printing every four seconds
Do Laundry
[4 seconds delay]
toDoList 1: Make Dinner
toDoList 2: Do the dishes
[4 seconds delay]
toDoList 1: Make Dinner
toDoList 2: Do the dishes
[4 seconds delay]
toDoList 1: Make Dinner
toDoList 2: Do the dishes
...
note
setInterval
is suitable for tasks that need to be repeated at regular intervals, such as animations or periodically updating data.
Conclusion
In JavaScript, setTimeout
is a valuable tool for delaying code execution, allowing precise timing for various tasks. To use it effectively, clear timers withclearTimeout
handles errors, and consider alternatives like Promises and async/await
for more efficient asynchronous programming. Exploring asynchronous techniques empowers developers to create responsive and faster applications. Embrace these concepts to become a proficient JavaScript developer and enhance your code's performance and user experience.
Subscribe to my newsletter
Read articles from Marilyn kalu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Marilyn kalu
Marilyn kalu
I'm a Front-End Developer and a Technical writer, I intend to share topics that I just learnt because someone out there might need it.