Time of the day loop

I want to do something like this

if (hour is > 9am && hour is < 8pm){
 setInterval(myFunction,60000)
}
else {
setInterval(myFunction,100000)
}

I want to execute myFunction less often after 8pm but the problem is that if user landed on the page at 2 pm it will always execute every minute unless script is refreshed. How can this be solved?

well i wouldnt use setInterval. (Consider what happens if I show up to your site at 7:59 PM.)

I’d have a look at the getHours function.

it would still be executing every 1 minute because I would only take an hour out of the Date object and therefore hr would be 7.

Reason I ask is that I want to execute myFunction more often while the office is open and less often when the office is not open. If the user lands on the page during the opening time and stays there beyond opening into the closing time myFunction will still execute every 1 minute because JS still thinks the hour is what it was when page was loaded

Which is why i wouldnt use setInterval. I’d use SetTimeout, and re-evaluate the time each time the function runs.

I know but even if I use that function do I have to recheck the time every time before execution?

  if (hours >= 15) {
    //check hour of the day here??
    setTimeout(executeEveryMinute, 1200000);
  } else {
    //check hoir of the day here?
    setTimeout(executeEveryMinute, 60000);
  }

that’s your check there.

i know but once you go into that loop and you stay there for a while the time will change after few hours if the user stays on the page.

can you show me pseudo code if possible so i can understand what you mean please

on each loop, you update hours. You can do it before the if, or as part of the condition.

i think i got it. make sense what you are saying. thank you!!

@m_hutley how do i mark this solved?

You just did :slight_smile:

1 Like