Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-30 02:02:28
Original
185 people have browsed it

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><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
Copy after login

}

setTimeout(function() {

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

}, millisTill10);

function openAPage() {

// Your function to perform the desired actions
Copy after login

}



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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!