0

I have an event_start time and I want to run a script 10 seconds after that event start but can't figure out how to trigger the script.

const date = Date().toString();
const currentDateParse = Date.parse(date);
const trigger = Date.parse(startTime) + 1000 * 10

Then this is how I'm attempting to trigger the script but it's not working. How do I start my function when the currentDateParse is equal to trigger. Or, put more simply, 10 seconds after the event starts.

if (currentDateParse = trigger)
   <function code underneath works already>
econobro
  • 315
  • 3
  • 17

2 Answers2

1

Calculate the time difference between now and when you want to trigger the script, and use setTimeout() to call it then.

const timediff = trigger - new Date().getTime();
setTimeout(function() {
    // do what you want
}, timediff);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you @barmar - you both answered my question so I marked it correct but have a follow up... my script is sending data to my server, but after 20 minutes my page falls asleep and the script doesn't run until I refresh. Is there a way to prevent this from happening? (Or prompt it from the server). – econobro Jan 13 '22 at 20:59
  • Sounds related to this question: https://stackoverflow.com/questions/6032429/chrome-timeouts-interval-suspended-in-background-tabs – Barmar Jan 13 '22 at 21:01
0

Try this (explanations below):

let startTime = "18:00";
let currentTime = new Date();
let target = new Date().parse(startTime);

let timeout = target - currentTime + 1000 * 10; // how long should it wait till the functions is executed

function runTenSecAfterEvent() {
  // do something here
}

setTimeout(runTenSecAfterEvent, timeout);

Explanations

After you calculated target (the start time) and currentTime, you need to know the time difference between them (timeout), so target minus currentTime. After that, you add the 10000ms.

And then you define the function which will be executed 10 seconds after the event occurred (runTenSecAfterEvent()).

Finally, you create a timeout.

nare214
  • 337
  • 2
  • 7
  • Thank you @natre214 - you both answered my question so I marked it correct but have a follow up... my script is sending data to my server, but after 20 minutes my page falls asleep and the script doesn't run until I refresh. Is there a way to prevent this from happening? (Or prompt it from the server). – econobro Jan 13 '22 at 20:59