In the world of web development, JavaScript plays an essential role in creating dynamic and interactive user experiences. One powerful aspect of JavaScript is its ability to control the execution of functions in response to time intervals, providing developers with the flexibility to create time-sensitive logic and repetitive actions within their applications. In this article, we will explore two prominent JavaScript timing mechanisms—setTimeout and setInterval—which allow us to delay function calls and execute them at specified intervals, respectively. Furthermore, we will discuss how to implement a function that is called every second in JavaScript, demonstrating the practical applications of these time-based utilities. By the end of this tutorial, you will have a solid understanding of these essential JavaScript concepts and be well-equipped to use them effectively in your own projects.
setInterval
or setTimeout
, which one to use?
Deciding whether to use setInterval
or setTimeout
depends on the specific use case and desired behavior in your application. Both methods provide time-based control over function execution, but they serve different purposes.
setInterval
: This method is used to repeatedly execute a function at a specified time interval. The function will continue to execute at that interval until the interval is cleared using theclearInterval
method. This is useful when you want to perform an action repeatedly at regular intervals, such as updating a countdown timer, polling a server for new data, or animating elements on the page.setTimeout
: This method is used to delay the execution of a function by a specified number of milliseconds. The function is called only once after the specified delay has elapsed. This is useful when you want to delay an action, such as showing a tooltip after a certain time, delaying a notification, or debouncing user input.
Let's consider two practical scenarios to demonstrate the usage of setInterval
and setTimeout
in real-world applications.
Scenario 1: Checking for daily updates using setInterval
Suppose you have a web application that needs to check for daily updates from an API every 24 hours. You can use setInterval
to achieve this as it allows you to execute a function repeatedly at regular intervals. In this case, you would set an interval of 24 hours (86,400,000 milliseconds).
function checkDailyUpdates() {
// Code to fetch updates from the API and update the application
}
// Set interval to check for updates every 24 hours (86,400,000 ms)
const dailyUpdatesInterval = setInterval(checkDailyUpdates, 86400000);
Remember to clear the interval when it is no longer needed or when the application is closed, using clearInterval(dailyUpdatesInterval)
.
Scenario 2: Displaying a daily reminder using setTimeout
Now, let's say you want to display a daily reminder notification to users at a specific time of day, such as 9:00 AM. In this case, you can use setTimeout
to achieve the desired behavior. First, calculate the time difference between the current time and the reminder time, then set a timeout to display the reminder.
function displayDailyReminder() {
// Code to display the daily reminder notification
}
function setDailyReminder() {
const currentTime = new Date();
const reminderTime = new Date(currentTime);
reminderTime.setHours(9, 0, 0, 0); // Set the reminder time to 9:00 AM
// Calculate the time difference between the current time and the reminder time
let timeDifference = reminderTime - currentTime;
// If the reminder time has already passed, add 24 hours to the time difference
if (timeDifference < 0) {
timeDifference += 86400000; // 24 hours in milliseconds
}
// Set a timeout to display the daily reminder
setTimeout(() => {
displayDailyReminder();
setDailyReminder(); // Recursively set the reminder for the next day
}, timeDifference);
}
// Call the function to set the initial reminder
setDailyReminder();
In this scenario, we used setTimeout
along with recursion to create a daily reminder. This approach provides more control over when the reminder is displayed, especially if the intervals between reminders can change or depend on specific conditions.
setTimeout()
 and the setInterval()
 methods are ancient parts of JavaScript. However, they are not obsolete or deprecated. For more complex scenarios, you should web workers rather than roll your own custom solutions built on setTimeout()
 or setInterval()
. However, both methods are still acceptable.
Using setInterval
method
On how to call a function every second in JavaScript, the setInterval
method is your best approach to achieving this. All we need is the function we want to call every second and the timeframe we want to repeat the function call. Just like setTimeout
method, only the function we want to call at an interval is required, but the delay parameter (default is 0
) is needed if we want to make sure to call the function at a specified interval.
Via the Windows and Worker interface, the setInterval
method calls a fixed time frame repeatedly, and the method returns an interval ID that can be used to identify the operation to be canceled out by the clearInterval
method (similar to clearTimeout
)
setInterval(function, delay, arg1, ..., argN)
The arg1...argN
are the arguments that will be passed on to the function
. Now, let’s illustrate the setInterval
method by logging the date and time every second. We create a function named timeAndDate
that logs the Date
object and passes the same function to the setInterval
method at 1000
milliseconds (which corresponds to 1 second). With this, we have called a function every second in JavaScript.
const timeID = setInterval(timeAndDate, 1000);
function timeAndDate() {
console.log(new Date());
}
Output
2022-11-09T05:21:20.263Z
2022-11-09T05:21:21.274Z
2022-11-09T05:21:22.277Z
2022-11-09T05:21:23.291Z
2022-11-09T05:21:24.291Z
The above output will continue for as long as possible. If we want to clear out the interval, we can make use of the clearInterval
method. All in all, to call a function every second, the code template above is a named function, all you need is add your own logic to your function and pass it to the setInterval
method. You can also make use of anonymous functions as seen below, and the value "Date"
is an argument passed to the anonymous function.
const timeID = setInterval(
(arg) => {
console.log(`${arg}: ${new Date()}`);
},
1000,
"Date"
);
Output
Date: Wed Nov 09 2022 06:21:48 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:49 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:50 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:51 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:52 GMT+0100 (West Africa Standard Time)
Using setTimeout method
setTimeout
is a JavaScript method that allows you to delay the execution of a function by a specified number of milliseconds. It is part of the global window
object in browser environments and can be accessed using window.setTimeout
. In Node.js, it is a part of the global object and can be called directly as setTimeout
.
setTimeout(callback, delay, arg1, arg2, ...)
Here,
callback
: The function to be executed after the specified delay.delay
: The time, in milliseconds (1/1000 of a second), after which the function should be executed. The actual delay might be slightly longer due to the nature of the JavaScript event loop.arg1
,arg2
, ...: Optional arguments that can be passed to the callback function when it is executed.
setTimeout
returns a unique identifier (a positive integer) that can be used to cancel the delayed function execution using the clearTimeout
method.
In this example, we will display a message in the console after a delay of 3 seconds (3000 milliseconds).
function showMessage(message) {
console.log(message);
}
// Set a timeout to call the showMessage function after a delay of 3 seconds
const timeoutId = setTimeout(showMessage, 3000, 'This message will be displayed after 3 seconds.');
// To cancel the timeout, use clearTimeout with the unique identifier returned by setTimeout:
// clearTimeout(timeoutId);
In this example, setTimeout
is used to call the showMessage
function after a 3-second delay. The message to be displayed is passed as an argument to the showMessage
function. Note that you can cancel the scheduled function execution using clearTimeout
with the unique identifier returned by setTimeout
.
Bonus Tip: Using async/await
in combination with Promise
In addition to setTimeout
and setInterval
, another useful and modern approach for managing time-based functions is the use of async/await
in combination with Promise. This method is especially useful when you want to manage the timing of asynchronous code execution, such as API requests, file reading, or any task that requires some time to complete.
Here's an example of a function that utilizes Promise
and async/await
to delay the execution of code:
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function delayedFunction() {
console.log('Starting the delayed function...');
// Wait for 3 seconds before proceeding
await delay(3000);
console.log('3 seconds have passed, continuing the function...');
}
// Call the delayed function
delayedFunction();
In this example, we define a delay
function that returns a Promise
and resolves it after the specified number of milliseconds using setTimeout
. We then create an async function (delayedFunction) that utilizes the await keyword to pause the execution of the function until the Promise is resolved. This approach allows you to manage the timing of your code in a more readable and structured manner, especially when dealing with complex asynchronous operations.
While this method is not a direct replacement for setTimeout
and setInterval
, it is a powerful technique for managing time-based and asynchronous code execution in a more modern and readable way. It is particularly useful when working with asynchronous tasks, chaining multiple delays or time-based actions, and managing code that depends on the completion of other tasks.
Summary
In summary, setTimeout
and setInterval
are essential JavaScript timing mechanisms that allow developers to control the execution of functions based on time. setTimeout
is used to delay a function call by a specified number of milliseconds, executing it only once, while setInterval
is used to execute a function repeatedly at regular intervals. These methods are particularly useful in scenarios like checking for daily updates, displaying notifications, or animating elements on a web page.
Additionally, modern JavaScript provides the async/await
syntax in combination with Promise
to manage time-based and asynchronous code execution in a more structured and readable way. This approach is particularly useful for chaining multiple delays, working with asynchronous tasks, or managing code that depends on the completion of other tasks.
References
setInterval() - Web APIs | MDN (mozilla.org)
What's the easiest way to call a function every 5 seconds