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

How to Schedule a JavaScript Function to Run at a Specific Time of Day?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 02:02:28186browse

How to Schedule a JavaScript Function to Run at a Specific Time of Day?

Scheduling a JavaScript Call for a Specific Time of Day

Consider the need to invoke a JavaScript function at a precise time each day, such as 10:00 AM. This task can be achieved through a combination of JavaScript functionality and the manipulation of time-related values.

Understanding the Code

The provided code attempts to open a new browser window at 10:00 AM and then repeatedly every minute. However, it needs refinement to function correctly.

Adjusting the Code for Accuracy

To modify the code for accurate scheduling:

<script type="text/javascript"><br>var now = new Date();<br>var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;</p>
<p>if (millisTill10 < 0) {</p><pre class="brush:php;toolbar:false">millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.

}

setTimeout(function() {

openAPage();
setInterval(openAPage, 60 * 1000); // Set the interval for subsequent calls

}, millisTill10);

function openAPage() {

// Your function to perform the desired actions

}



The code has been modified as follows:

  1. The calculation of millisTill10 is adjusted to ensure that it correctly calculates the milliseconds until 10:00 AM today or tomorrow, depending on the current time.
  2. A check is added to handle scenarios where the current time is past 10:00 AM. In such cases, the code schedules the call for 10:00 AM the next day by adding 86400000 milliseconds (one day in milliseconds).
  3. The setInterval() call is placed within the setTimeout() callback to schedule the repeated calls for every minute.

By incorporating these changes, the provided code will now correctly execute the desired function at 10:00 AM and continue to do so every minute.

The above is the detailed content of How to Schedule a JavaScript Function to Run 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