Created
December 9, 2022 02:54
-
-
Save kush-agra/946518d7b1763e1f331280dbca4e82d9 to your computer and use it in GitHub Desktop.
Make api call / call a function at a specified time approximately accurate to the millisecond
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function makeApiCall(time) { | |
// Get the current date and time | |
var now = new Date(); | |
// Set the date and time for the specified time | |
var specifiedTime = new Date(); | |
specifiedTime.setHours(time.hours); | |
specifiedTime.setMinutes(time.minutes); | |
specifiedTime.setSeconds(0); | |
specifiedTime.setMilliseconds(0); | |
// If it's after the specified time, set the date for the next occurrence of that time | |
if (now > specifiedTime) { | |
specifiedTime.setDate(specifiedTime.getDate() + 1); | |
} | |
// Calculate the time until the next occurrence of the specified time | |
var timeUntilSpecifiedTime = specifiedTime - now; | |
// Set a timeout to make the API call at the next occurrence of the specified time | |
setTimeout(function() { | |
// Make the API call here | |
}, timeUntilSpecifiedTime); | |
} | |
// Make an API call at 9am | |
makeApiCall({hours: 9, minutes: 0}); | |
// Make an API call at 1pm | |
makeApiCall({hours: 13, minutes: 0}); | |
// Make an API call at 11pm | |
makeApiCall({hours: 23, minutes: 0}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment