0

I have a function which runs every 3 minutes 24/7 using setTimeout(). The problem is that it fetches data from an API that have an maximum of request a month. I want to run it as often as a can but it´s unnecessary to do so when i am a sleep because of the waste of requests. How can in addition only run my script between for example 06:30:00 and 20:00:00?

jaikl
  • 971
  • 2
  • 9
  • 23

2 Answers2

1

You will need both setTimeout and Date() to achieve this : for e.g.

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
     millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

For more details please follow this

emme
  • 215
  • 1
  • 8
  • Thanks! can you further explain more how this works. i understand that the script won´t start until it´s 10 am, but what time will it stop and how to i do if i want different start and end time? – jaikl Jan 19 '17 at 07:53
  • @jaikl You can set start time by changing values in [Date()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) :`new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);` – emme Jan 19 '17 at 08:48
  • @jaikl And to end to need to change **millisTill10** value according to the time you want to start it again. Also you can use [setInterval()](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) – emme Jan 19 '17 at 08:50
  • Can you give my an quick example as you did above? – jaikl Jan 19 '17 at 09:04
  • @jaikl Have a look at [this answer](https://stackoverflow.com/questions/18070659/run-javascript-function-at-regular-time-interval/18070683#18070683) , he has explained it very well. – emme Jan 19 '17 at 09:19
  • Sorry for not understanding but how to i make my function run every x seconds until 20,00,0,0 and then start at 06,20,0,0 again? I took your example above and substituted it to this: var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 06, 20, 0, 0) - now; if (millisTill10 < 0) { millisTill10=0; millisTill10 += 100000; } setTimeout(myFunction, millisTill10);. Is I understand, this code will run until 23:59 and then wait until 06:20? – jaikl Jan 19 '17 at 09:56
0

I have tested and verified following code. Mine is 7:22 PM which comes under these timings and it executes very well.

// get todays strict timings
// 06:30:00 and 20:00:00

setInterval(function() {
  lowerDate = new Date();
  lowerDate.setHours(6);
  lowerDate.setMinutes(30);
  lowerDate.setSeconds(0);


  upperDate = new Date();
  upperDate.setHours(20);
  upperDate.setMinutes(0);
  upperDate.setSeconds(0);

  todayDate = new Date();

  if (todayDate > lowerDate && todayDate < upperDate)
    console.log("execute"); // execute only if in between these times
}, 3 * 60 * 1000) //Every 3 minutes
BILAL AHMAD
  • 686
  • 6
  • 14