Delay the execution of Javascript code for one hour daily over the course of a month

Updated Question: Despite the larger issue, can someone explain why the sleep function in the code below doesn't provide a one-hour pause in execution? Understanding this would be greatly appreciated.

I am trying to trigger a JavaScript function that runs continuously for one month within a Chrome extension but pauses its execution for one hour every day between 8:15am and 9:15am.

Here is my attempted code, but the delay from the sleep() function is not working:

function(){ //triggered on button press, an extremely long process
    function sleep(miliseconds) {
        var currentTime = new Date().getTime();
        while (currentTime + miliseconds >= new Date().getTime()) {
        }
     }

    var data_array = ["fake_data1", "fake_data2", /*...*/ "fake_data923421"];
    for (let i=0; i<data_array.length; i++){
        var today = new Date();
        var hours = today.getHours();
        var minutes = today.getMinutes();
        if(hours >= 8 && minutes >= 15){
            sleep(3600000);
        }
        //do things if it's not 8:15-9:15am
        setTimeout(function() {
            //things here happen as expected with setTimeout delay
            //have had issues using setTimeout sometimes, but not consistently
            //hence the use of the sleep() function (credit goes to SO)
        }, (i+1)*10000);
    }
});

Important Notes: - I am open to alternative approaches to achieving this goal. - There are valid reasons for using JavaScript and running the script constantly for a month. - No users will interact with the page, so UI responsiveness is not relevant

Bonus Points - considering this is in a Chrome extension, if there is a way to store data without using an array and mark each value processed to resume from where it left off after stopping, that would be helpful. While I could set up a database or web service, I prefer a quick and easy solution for this one-time, non-production code.

Answer №1

If anyone is facing the same issue... I couldn't figure out why the sleep function mentioned above wasn't working for me, but after making a few tweaks with a do-while loop, it started working perfectly.

function sleep(miliseconds) {
   var d = new Date();
   var d2 = null;
   do { d2 = new Date(); }
   while(d2-d < miliseconds);
}

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

Urgent dependency alert: calling for a necessity (sequelize) in next.js is a vital element

I'm encountering a challenge with integrating sequelize into my Next.js 13 project to connect my API routes with the database. I keep receiving errors that say "Critical dependency: the request of a dependency is an expression." import * as pg from &a ...

The JQuery datepicker fails to provide the date in the format mm/dd/yy

Recently, I attempted to transform a date into the dd/mm/yy format using JQuery datepicker. Unfortunately, my results displayed in the dd/mm/yyyy format instead. Here is the code snippet that I utilized: chkIn = $.datepicker.formatDate("dd/mm/yy", cinDate ...

Making a list of members from an array of objects

Let's say I have a collection of items structured like this: var itemList = [ { date: '22/9/2016', status: 1, id: '11111' }, { date: '23/9/2016', status: 1, id: '22222' }, { date: '24/9/2016&ap ...

Incorporate Aria Label into a Website Link

Currently working on enhancing website accessibility. I have identified a close menu button that lacks an Aria Label, and my goal is to rectify this using JavaScript. Although I am utilizing the script below to target the specific ID and add the attribute ...

Step-by-step guide to creating a polyline on OpenStreetMap using JavaScript arrays

I am looking to create a polyline on OpenStreetMap using a marker array object. Currently, I am retrieving all marker (longitude, latitude) values from the database and based on those markers, I want to draw a polyline to display the route of a specific ...

Retrieve the report information and present it in a HTML data table using a REST API

My understanding of REST API and Javascript is limited, but I now find myself needing to interact with a third-party company's REST API for email reporting purposes. The data can be accessed through a GET method using a URL with a specific TOKEN: {pl ...

The .push method in Javascript is failing to execute

I'm facing a challenge with this particular code snippet. Essentially, I am attempting to loop through an array of Word objects and categorize them based on word type using a switch statement. This process is triggered by jQuery listening for a button ...

Error encountered while importing Blender model into Three.js: Uncaught TypeError - Unable to access property 'x' as it is undefined

I've been attempting to transfer a 3D model from Blender into a Three.js project, but I keep encountering this error: Uncaught TypeError: Cannot read property 'x' of undefined. The issue seems to be stemming from the following piece of code: ...

disable any other active toggle in a vue component

Exploring JavaScript and how to accomplish the following tasks Snapshot The issue I am facing is that if I click on a product, and then click on settings, both are open. However, I want only the currently clicked toggle to be open. For instance, if I cl ...

Extracting multiple values using the .find method in JQUERY / JavaScript

I'm facing an issue with my JSP page form. When I submit the form, it generates a JSON string which is sent via AJAX post. The problem arises when I try to extract multiple values from the form using the following method: .find('input[name=ite ...

Express JS: The requested resource does not have the 'Access-Control-Allow-Origin' header

Currently, I am encountering an issue with my API running on a server and the front-end client attempting to retrieve data from it. Previously, I successfully resolved the cross-domain problem, but now it seems like something has changed as I am receiving ...

Optimizing jqGrid: Enhancing saveRow function to properly synchronize with editRow function

Exploring how to customize jqGrid's add function for my own needs. I have a navButton with specific requirements: When the user clicks the button, a new row in edit mode should appear on the grid. Once the user enters data and presses enter, the dat ...

Leveraging ForEach to merge two arrays and generate a fresh entity

I am in search of my final result which should be as follows: result = [{x: '12/12', y: 90 }, {x: '12/11', y: 0}, {x: '12/10', y: 92}, {x: '12/9', y: 0}, ... ] Currently, I have two arrays to work with. The first a ...

Information vanishes on mobile devices

After creating a messaging app using React, TypeScript, and Firebase, everything works smoothly locally on both desktop and mobile. However, once the app is deployed, a problem arises specifically on mobile devices. The message input component ("sendMessa ...

Display the next page once two distinct service requests have been received

When I need to display a page after retrieving data from two different services, service1 and service2, how can I achieve this without nesting the second service call inside the first one? Instead of chaining the service calls, I want to make separate req ...

How can a JavaScript array be transmitted as a JSON value?

Is there a method to pass a JavaScript array as a JSON variable in my AJAX query? ...

Passing along a request using Node.js

I am facing an issue in my project where I need to redirect requests received by a nodejs endpoint to a .NET 7 web API endpoint. The nodejs endpoint is triggered by an external party and it receives the request as expected. However, there seems to be a pro ...

Unable to find the Popper component in Material UI

Material-UI version "@material-ui/core": "^3.7.0" I have a requirement to display Popper on hover over an element, but unfortunately, the Popper is not visible. This section serves as a container for the Popper component. import PropTypes from &apos ...

Ways to confirm the presence of specific keys in a JSON:

After successfully converting an excel sheet's content into a JSON format, my next task is to perform some validation on it. The requirement is to ensure that the jsonData variable contains specific keys in a particular order: Breakfast, Lunch, Snack ...

Synchronization issues arise when attempting to update the localStorage

Whenever I switch to dark mode, the update doesn't reflect in _app unless I have two tabs opened and trigger it in one tab. Then, the other tab gets updated with dark mode toggled, but not the tab where I pressed the toggle. I am using useSettings in ...