Home > Article > Web Front-end > How to Schedule JavaScript Function Calls at Specific Times?
Scheduling Function Calls at Specific Times
To execute a JavaScript function at a particular time of day, you can utilize a combination of setTimeout and Date objects. Here's how you can achieve this:
<code class="javascript">// Calculate the time in milliseconds until the desired hour var now = new Date(); var targetTime = new Date(); targetTime.setHours(10, 0, 0, 0); // Set the target time to 10:00:00 AM var millisTillTarget = targetTime - now; // If the target time is in the past (e.g., it's already 10:00 AM), adjust it to the next day if (millisTillTarget < 0) { millisTillTarget += 86400000; // Add 24 hours } // Schedule the function call using setTimeout setTimeout(function() { // Your function here (e.g., open a page or display an alert) }, millisTillTarget);</code>
In this code:
Example: To open a specific page (e.g., Google) at 10:00:00 AM daily:
<code class="javascript">setTimeout(function() { window.open("http://google.com", "_blank"); }, millisTillTarget);</code>
Note: This approach executes the function only once at the specified time. If you want to repeat the function execution at regular intervals, you can use setInterval instead.
The above is the detailed content of How to Schedule JavaScript Function Calls at Specific Times?. For more information, please follow other related articles on the PHP Chinese website!