Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

41
Views
Trigger client side javascript based on datetime

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>
7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
7 months ago · Juan Pablo Isaza Report

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.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs