Home  >  Article  >  Web Front-end  >  How to Execute a JavaScript Function at a Specific Time of Day?

How to Execute a JavaScript Function at a Specific Time of Day?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 22:20:02298browse

How to Execute a JavaScript Function at a Specific Time of Day?

Call a JavaScript Function at a Specific Time of Day

Question:

How can I trigger a JavaScript function at a predefined time of day, say 10:00 AM?

Solution:

To schedule a function execution at a specific time, you can leverage JavaScript's setTimeout() method in conjunction with Date to calculate the remaining time.

<code class="javascript">var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
    millisTill10 += 86400000; // adjust for tomorrow if past 10 AM
}
setTimeout(function() {
    // Your function to be executed at 10 AM
}, millisTill10);</code>

Explanation:

  1. now stores the current time.
  2. millisTill10 calculates the milliseconds remaining until 10:00 AM.
  3. If millisTill10 is negative, it means it's past 10 AM. In this case, we add 86400000 milliseconds (one day) to schedule the function for 10 AM the next day.
  4. setTimeout() schedules the function execution after the specified number of milliseconds (millisTill10).

The above is the detailed content of How to Execute a JavaScript Function at a Specific Time of Day?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn