Executing a Javascript function according to set times of the day

After successfully implementing the code below for a specific time of day such as 4pm, I am now looking to extend its functionality. Ideally, I would like to be able to call this function at various other times throughout the day.

For example, I may want to trigger it at 7am, 11am, or even multiple times at 7am, 11am, and 4pm. Any assistance with achieving this flexibility would be highly appreciated.

setInterval(function interval(){    
    var now = new Date();
    var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 0, 0, 0) - now;
    if (time < 0) {
         time += 86400000;
    }    
    setTimeout(function () {
        my_function();
        timeout();
    }, time);
    return interval;
}(),1800000);

Answer №1

Have you considered implementing a solution that checks the current hour every hour to see if it matches a preset array of desired hours, and if there's a match, triggers a custom function?

function checkHour(){
    var d = new Date();
    var targetHours=[1,13,17,23];
    if(targetHours.indexOf(d.getHours()) != -1){
        executeCustomFunction();
    }
    setTimeout(checkHour, calculateMillisecondsLeft());

}

function executeCustomFunction(){
    console.log('Great! It is now 1am, 1pm, 5pm, or 11pm!');
}

function calculateMillisecondsLeft(){
    var d = new Date();
    return 1000*60*60 - (d.getMinutes()*1000*60 + d.getSeconds()*1000+ d.getMilliseconds());    
}

setTimeout(checkHour, calculateMillisecondsLeft());

Answer №2

Let's try a new approach. This function sets timeouts for each specified hour, and then renews them whenever one of the timeouts triggers:

function setTimers(hour) {
    var current = new Date(),
        target = new Date(current.getFullYear(), current.getMonth(), current.getDate(), 
                        hour, 0, 0, 0),
        difference = target - current;

    if (difference < 0) {
        difference += 86400000;
    }
    setTimeout(function () {
        triggerFunction();
        setTimers(hour);
    }, difference);
}

var hours = [7, 11, 16];

hours.forEach(setTimers);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to use static imports with Typescript?

Let's imagine that Object is a module that can be imported and currently we are using Object.getOwnPropertyNames. Is it possible to write the following code instead: import {getOwnPropertyNames} from 'Object'; ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Self-referencing object identifier

Having trouble articulating this question, but I'm attempting to develop a JavaScript object that manages an array of images for reordering and moving purposes. function imgHandler(divname) { this.imgDiv = divname; this.img = Array("bigoldliz ...

Utilize interpolation with ES6 and an Angular 1.4 directive

Currently experimenting with the unique ES6 + Angular combination and facing a challenge in interpolating an html string within a directive that includes scope bindings. We have attempted the following approach: Current scenario The code below is functi ...

A guide on updating a JSON object based on specific criteria

I'm dealing with two JSON files here - the first one is named origin.json, and the second one is called newData.json. My goal is to update the child value of Origin based on the data in NewData. However, I only want this update to impact items that a ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

Change the position of an HTML image when the window size is adjusted

My web page features a striking design with a white background and a tilted black line cutting across. The main attraction is an image of a red ball that I want to stay perfectly aligned with the line as the window is resized, just like in the provided gif ...

Turning a singular string into multiple strings within an array

Having recently started coding, I encountered my first issue that I can't seem to solve. The problem is with a string "XX|Y1234$ZT|QW4567" where I need to remove both $ and |, then push the elements into an array like this: ['XX', 'Y12 ...

Utilizing Vue.js to apply conditional statements or filters on v-for generated outputs

Currently, I am working on organizing my results by category. I believe there is room for improvement in the way it's being done: <div><h2>Gloves</h2></div> <div v-for="stash in stashes" :key="stash.id"> <div v-for= ...

What is the maximum amount of information that can be stored in a data attribute within the DOM?

Occasionally, I find myself wanting to include a substantial amount of data on the webpage in order to minimize additional AJAX calls for dynamic content. However, I am concerned about potential performance implications. Is there a penalty I should be aw ...

Unable to perform a POST request and send JSON data using AJAX with jQuery at the

It seems like there may be a server issue causing this problem, and unfortunately, I don't have access to our server to troubleshoot. I was hoping that someone else might have a solution or could help me understand the root cause of the issue. The is ...

Capturing the Facebook Login Event to dynamically modify the content of the main webpage

My current project involves creating a Facebook-based login system using JavaScript. When a user clicks a button, I want one div to be replaced by another if the user is already logged in to Facebook. If they are not logged in, I prompt them to enter their ...

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...

Customizing Event Colors in FullCalendar by Comparing Dates

Recently, I began experimenting with arshaw's fullcalendar. Throughout the development process, I scoured websites for solutions on how to change event colors based on both the event dates and the current date. This HTML, PHP, and Javascript code is t ...

AJAX Post data transmission on the network: Enhancing data formatting

For my AJAX post call, I need to format the data differently. The server is expecting the data in a specific format when viewed in Chrome Network Headers details. My task is to update the JavaScript code below to meet this formatting requirement: percenta ...

Error: Unable to access document property as it is null and cannot be read

Trying to launch a new window from another new window triggers the error above. This is my SystemModal.js const SystemModal = (props) => { console.log(props) const [visible, setVisible] = useState(false); return ( <Row> ...

Tips for Transferring Values Between Multiple Dropdown Menus with jQuery

Hello there, can anyone guide me on how to transfer selected items from one multiple combo box to another multi-combo box? I would really appreciate it if someone could provide an example for this scenario. <HTML> <HEAD> <TITLE></T ...

Converting user input from a string to an object in JavaScript: a comprehensive guide

Is there a way to transform user input string into objects when given an array of strings? ["code:213123", "code:213123", "code:213123"] I am looking to convert this array into an array of objects with the following format: [{code: "213123"},...] ...

Randomize elements with the click of a button

Every time the page refreshes, the words shuffle around. For instance, "May I# know# your name?" shuffles to "know May I your name". To display the correct sentence with "#" as "May I know your name?", click the SHUFFLE button to trigger the shuffling. HT ...