Skip to content Skip to sidebar Skip to footer

Javascript If For Various Days And Hours

I need to set a javascript function to only run only these day/hour combinations - Sun (none), Mon (4-5,8-23), Tue-Thu (0-5,8-23), Fri (0-5,8-21), Sat (1-3,8-12,16). Is this the co

Solution 1:

This is an easier way to write what you're trying to do. Set a flag to false, and change it to true if one of your day/hour combinations is met. Run your code at the end if your flag is true. Abstract the hour checking into a separate function. There's plenty of other ways to make this better but here's my attempt.

var date = new Date(); 
var hour = date.getHours(); 
var day = date.getDay();

function isBetween(testNumber, lowerLimit, upperLimit) {
  return testNumber >= lowerLimit || testNumber <= upperLimit;
}

var flag = false;

if(day === 1 && (isBetween(hour, 4, 5) || isBetween(hour, 8, 23))) {
  flag = true;
}

if(isBetween(day, 2, 4) && (isBetween(hour, 0, 5) || isBetween(hour, 8, 23))){
  flag = true;
}

if(day === 5 && (isBetween(hour, 0, 5) || isBetween(hour, 8, 21))) {
  flag = true;
}

if(day === 6 && (isBetween(hour, 1, 3) || isBetween(hour, 8, 12) || hour === 16)) {
  flag = true;
}

if(flag) {
  // do something
}

The way you've written it, the code is pretty difficult to read and maintain. If there's a change you have to make in the future, you'll have to read through that massive if statement and be careful not to break anything. This way, each piece of logic is separate and if you need to change a piece, you don't have to worry about breaking everything. The code is also easier for anyone else who might have to work on your project to read. Hope this helps!


Solution 2:

To simplify your code and make it easier for other to understand and debug, put the days the code is supposed to run in an array using the day and hour. So, Monday at 4 o'clock would be stored as '2_4'. Then loop through the array to check if the current day and time matches any of array values, and if it does, execute your code. Here is an example:

var date = new Date();
var hour = date.getHours();
var day = date.getDay();
var combined = day+'_'+hour;

//add additonal days when the code should run
var run_on = ['2_4','2_5','3_0', '3_1']; 

for (i = 0; i < run_on.length; i++){
    if (combined == run_on[i]){
    //execute your code
    break;
    }  
} 

This reduces the code significantly and if there are any times or dates that need to be added or removed, you can easily do so without having to rewrite your logic every time.


Post a Comment for "Javascript If For Various Days And Hours"