Categories
JavaScript Answers

How to call a JavaScript function at a specific time of day?

Spread the love

Sometimes, we want to call a JavaScript function at a specific time of day.

In this article, we’ll look at how to call a JavaScript function at a specific time of day.

How to call a JavaScript function at a specific time of day?

To call a JavaScript function at a specific time of day, we call setTimeout with the number of milliseconds between now and the date and time we want to call the function.

For instance, we write

const etaMs = new Date(2023, 0, 21, 17, 0).getTime() - Date.now();
const timeout = setTimeout(() => {}, etaMs);

to call setTimeout with the function we want to run after etaMs milliseconds has elapsed.

We subtract the timestamp of the future date time by the timestamp of the current timestamp to get the number of milliseconds to wait before we call the setTimeout callback.

Conclusion

To call a JavaScript function at a specific time of day, we call setTimeout with the number of milliseconds between now and the date and time we want to call the function.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.