What is the best way to utilize distinct arrays for various days of the week?

Managing school bell schedules can be challenging, especially when there are different schedules for different days. In this case, we have two arrays containing sets of dates and times for a school bell schedule. The challenge is to pull the array for Wednesdays only on Wednesdays, while allowing the other array to work on all other days besides Wednesday. The purpose of this code is to display a countdown timer if the current time falls between the start and end times specified in the array.

//start of code
var d = new Date(2019);
function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  return {
    'total': t,
    'minutes': minutes,
    'seconds': seconds
  };
}
var myVar;


    myVar = setInterval(function(){window.location.reload(1);}, 1000);


function myStopFunction() {
  clearTimeout(myVar);
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  clock.style.display = 'block';
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);



    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
 }



  updateClock();
  var timeinterval = setInterval(updateClock, 1000);

}

var windowObjectReference;

function openRequestedPopup() {
  windowObjectReference = window.open(
    "file:///C:/Users/Darren%20Blount/OneDrive/COUNTDOWN/5_timer.html", 
"DescriptiveWindowName", 'height=30000,width=40000, left=40000, resizable=yes,scrollbars=yes,toolbar=yes, status=yes');


var monthNames = ["January", "February", "March", "April", "May", "June",
                  "July", "August", "September", "October", "November", 
"December"];
var d = new Date();
var currentMonth = monthNames[d.getMonth()];

var DayNames = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", 
"12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", 
"24", "25", "26", "27", "28", "29", "30", "31"];
var g = new Date();
var currentDay = DayNames[g.getDay()];



var wednesday /* Havenot worked into code*/= [
    // Daily Bell Schedule
    ['Oct 30, 2018 7:50:49', 'Oct 30, 2018 8:00:49'],
    //AAP
    ['Oct 30, 2018 9:29:49', 'Oct 30, 2018 9:34:49'],
    //1st Block - 2nd Block
    ['Oct 30, 2018 9:58:49', 'Oct 30, 2018 10:03:49'],
    //2nd Block - 1st Half 3rd Block

    ['Oct 30, 2018 11:49:49', 'Oct 30, 2018 11:37:49'],
    //1st Lunch - 3rd Block
    ['Oct 30, 2018 12:02:49', 'Oct 30, 2018 12:07:49'],
    //2nd Lunch - 2nd Half of 3rd Block
    ['Oct 30, 2018 12:42:49', 'Oct 30, 2018 12:47:49'],
    //3rd Block - 4th Block
    ['Oct 30, 2018 13:36:49', 'Oct 30, 2018 13:41:49']
];

const schedule /*Everyday*/= [
    ['Sep 11, 2018 7:50:49', 'Sep 11, 2018 8:00:49'],
    //AAP
    ['Sep 11, 2018 9:29:49', 'Sep 11, 2018 9:34:49'],
    //1st Block - 2nd Block
    ['Sep 11, 2018 9:58:49', 'Sep 11, 2018 10:03:49'],
    //2nd Block - 1st Half 3rd Block
    ['Sep 11, 2018 11:49:49', 'Sep 11, 2018 11:37:49'],
    //1st Lunch - 3rd Block
    ['Sep 11, 2018 12:02:49', 'Sep 11, 2018 12:07:49'],
    //2nd Lunch - 2nd Half of 3rd Block
    ['Sep 11, 2018 12:42:49', 'Sep 11, 2018 12:47:49'],
    //3rd Block - 4th Block
    ['Sep 11, 2018 1:36:49', 'Sep 11, 2018 1:41:49']
];


const schedule = [
    [currentMonth + currentDay + '2019 13:40:00', currentMonth + currentDay 
+ '2019 14:30:00']
]

for(let i=0; i<schedule.length; i++){
// pull them straight into Date objects
const startDate = new Date(schedule[i][0]);
const endDate = new Date(schedule[i][1]);

// Make a new Date for setting it for today, then set the hours based off 
the schedule
let startTime = new Date();
startTime.setHours(startDate.getHours(), startDate.getMinutes(), 
startDate.getSeconds());
let endTime = new Date();
endTime.setHours(endDate.getHours(), endDate.getMinutes(), 
endDate.getSeconds());

// Easier way to just get the ms and then the same check
const currentMs = Date.now();
if(endTime.valueOf() > currentMs && currentMs >= startTime.valueOf() ){
    initializeClock('clockdiv', endDate);
      openRequestedPopup();
        myStopFunction();
        setInterval(function(){window.location.reload(5);}, 306000);
        setTimeout(function () { windowObjectReference.close();}, 305000);
        }
}

Answer №1

In order to achieve the desired outcome, one can use the following method to determine the current day using getDay() function (e.g. Sunday is 0 and Wednesday is 3).

var d = new Date();
var today = d.getDay();

var wednesday = [
    // Daily Bell Schedule
    ['Oct 30, 2018 7:50:49', 'Oct 30, 2018 8:00:49'],
    //AAP
    ['Oct 30, 2018 9:29:49', 'Oct 30, 2018 9:34:49'],
    //1st Block - 2nd Block
    ['Oct 30, 2018 9:58:49', 'Oct 30, 2018 10:03:49'],
    //2nd Block - 1st Half 3rd Block

    ['Oct 30, 2018 11:49:49', 'Oct 30, 2018 11:37:49'],
    //1st Lunch - 3rd Block
    ['Oct 30, 2018 12:02:49', 'Oct 30, 2018 12:07:49'],
    //2nd Lunch - 2nd Half of 3rd Block
    ['Oct 30, 2018 12:42:49', 'Oct 30, 2018 12:47:49'],
    //3rd Block - 4th Block
    ['Oct 30, 2018 13:36:49', 'Oct 30, 2018 13:41:49']
];

var everyday = [
    ['Sep 11, 2018 7:50:49', 'Sep 11, 2018 8:00:49'],
    //AAP
    ['Sep 11, 2018 9:29:49', 'Sep 11, 2018 9:34:49'],
    //1st Block - 2nd Block
    ['Sep 11, 2018 9:58:49', 'Sep 11, 2018 10:03:49'],
    //2nd Block - 1st Half 3rd Block
    ['Sep 11, 2018 11:49:49', 'Sep 11, 2018 11:37:49'],
    //1st Lunch - 3rd Block
    ['Sep 11, 2018 12:02:49', 'Sep 11, 2018 12:07:49'],
    //2nd Lunch - 2nd Half of 3rd Block
    ['Sep 11, 2018 12:42:49', 'Sep 11, 2018 12:47:49'],
    //3rd Block - 4th Block
    ['Sep 11, 2018 1:36:49', 'Sep 11, 2018 1:41:49']
];

if(today ===3){
  console.log("Wednesday", wednesday)
}else{
  console.log("not wednesday", everyday)
}

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

How to use jQuery to determine if an image has finished loading

I'm facing an issue with the code below, it's not functioning properly: var timeoutID=0; var currentImage=0;//first image is position 0 in arrImages array var arrImages=[bla bla bla array of image URLs]; function slideShow() { if($('#my ...

How can I apply a class to a list item when clicked using Vue.js and a template component generated by v-for loop?

I'm struggling to add an active class to a list item in a template component when it's clicked, making sure that only one item can have the class at a time. I've attempted different solutions such as passing a new data object on click and r ...

Ways to eliminate the constant presence of the 'loading' cursor on screen

Currently, I have an interval in place that triggers an AJAX call to check for updates on the page (similar to how Facebook or StackExchange handle notifications). However, this call is causing two issues - it changes the cursor to a 'progress' o ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Utilizing Express middleware to serve routes in Sails.js

I am currently working on a sails app where the routes and static assets are served from the root location, which is functioning properly. However, I am looking to integrate an express middleware to serve these routes and assets from a specific path. To s ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

Having trouble with Grunt and Autoprefixer integration not functioning properly

Joining a non-profit open source project, I wanted to contribute by helping out, but I'm struggling with Grunt configuration. Despite my research, I can't seem to figure out why it's not working. I am trying to integrate a plugin that allow ...

Nested pages are causing jQuery plugins to malfunction

I am currently working on a website, but I am facing some issues with the product listing pages and the tips and tricks page. It appears that there is an issue with jMenu and jFlipBook plugins not functioning properly. Since I didn't develop the origi ...

Triggering a sweet alert on a mouse click

Here is a code snippet I found on . It shows an alert box that doesn't disappear when clicked outside of it. swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, ...

Discover the secrets to obtaining live website information using Google Script!

I am looking to retrieve the exchange rate data from a specific website. My understanding is that the website is dynamic (I'm still new to javascript) and the data is not easily accessible. Can anyone guide me on how to extract the exchange rates? For ...

When working with an associative array, the shuffle() function may not behave as intended

Interested in creating a quiz and here's the array: $questions = array("1+1"=>2,"5+2"=>7,"5+9"=>14,"3+5"=>8,"4+6"=>10,"1+8"=>9,"2+7"=>9, "6+7"=>13,"9+3"=>12,"8+2"=>10,"5+5"=>10,"6+8"=>14,"9+4"=&g ...

The React component fails to re-render upon the initial state update

Currently, I am working on a straightforward survey that requires simple Yes or No answers. The questions are stored in a separate file called QuestionsList.js: Here is the list of questions: const QuestionsList = [ "Do you believe in ghosts?", "Have you ...

Calculating the total of selected values in Checkboxes and Selectors using KnockoutJS

I have already created this using jQuery. You can view it on JSFiddle: JSFiddle HTML: <div class="container"> <header> <h3>The Crazy Things We'll Do for Money</h3> <div class="small"><em>An ele ...

Retrieve documents from MongoDB where the array includes a specific field within a document

The data stored in my collection("users") appears as follows: { _id: ObjectID(...), verifiedFields: { email: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f782849285b7928f969a879b92d994989a">[email  ...

Node JS GET request using fetch stops displaying console outputs after a certain duration

I am currently working on building a calendar application using node, mongodb, html, css, and javascript. The main goal is to allow users to input dates as events which can be displayed dynamically. I am facing an issue where, upon trying to retrieve these ...

Using a Javascript Function to Transform Raw JSON Data into a Facebook Standard Event

Currently working on creating a custom JavaScript function to convert the JSON formatted track event into the corresponding Facebook Pixel event. The track event is placed on an e-commerce site as shown below: analytics.track('Product List Viewed&ap ...

Floating navigation bar that appears and disappears as you scroll

My webpage has a dynamic navbar that consists of two parts: navbarTop and navbarBottom. The navbarTop should appear when the user has scrolled down more than 110 pixels, while the navbarBottom should show up when the user scrolls up. The issue I am facing ...

Complete the transparent logo by showing the progress of the page loading

I am pondering the idea of filling in a logo based on the percentage of the page load. My initial thoughts are to use a gif, but I wonder if syncing a gif with the % of page load is really possible. Another idea is to have 100 images that change out depen ...

Issue: Unhandled rejection TypeError: Unable to access properties of an undefined variable (retrieving 'data')

Currently, I am developing applications using a combination of spring boot for the backend and react for the frontend. My goal is to create a form on the client side that can be submitted to save data in the database. After filling out the form and attemp ...

Code to show HTML element using a mix of radio buttons

Seeking assistance as a beginner after spending hours struggling with my project while sipping coffee and Red Bull. I've tried various solutions from StackOverflow but couldn't find success. Any experienced web developers willing to lend a hand? ...