JavaScript: Execute functions automatically based on a pre-defined timeline

269 Views Asked by At

I am trying to build a web app that will execute JS functions for the user automatically, based on a pre-defined time.

For example: I have the following functions on a webpage:

  • function a () {do stuff}
  • function b () {do some other stuff}
  • function c () {do other stuff}

and a JSON timeline loaded per user:

"timeline":[
    {"ontime":" 00:00:00,000", "execute_func":"a"}, 
    {"ontime ":" 00:00:02,000", "execute_func":"b"}, 
    {"ontime ":" 00:00:07,000", "execute_func":"c"}, 
    {"ontime ":" 00:00:08,000", "execute_func":"a"}, 
    {"ontime ":" 00:00:13,000", "execute_func":"c"}
...
]

Is there a way to trigger these functions automatically, based on the order and timing they appear in "timeline"?

Many thanks in advance for any help!

1

There are 1 best solutions below

4
On BEST ANSWER

First problem with your JSON, it is not right. You can make it better like this:

"timeline": [
  {"ontime": "00:00:00,000", "execute_func": "a"}, 
  {"ontime": "00:00:02,000", "execute_func": "b"}, 
  {"ontime": "00:00:07,000", "execute_func": "c"}, 
  {"ontime": "00:00:08,000", "execute_func": "a"}, 
  {"ontime": "00:00:13,000", "execute_func": "c"}
  ...
]

Note the keys spacing... There was a space after ontime, which shouldn't be there...

You need to set up a timing event handler function, which executes every second like this:

setTimeout(function () {
  // Execute every 1 second.
  // Get the current time.
  curTime = (new Date());
  var curTime = ("0" + curTime.getHours()).substr(-2) + ":" + ("0" + curTime.getMinutes()).substr(-2) + ":" + ("0" + curTime.getSeconds()).substr(-2);
  if (typeof getFunctionOnTime(curTime) == "function") {
    getFunctionOnTime(curTime)();
  }
}, 1000);

The getFunctionOnTime function will return the function, if not, it returns false.

function getFunctionOnTime(time) {
  for (var i = 0; i < timeline.length; i++) {
    if (timeline[i].ontime == time) {
      return (window[timeline[i].execute_func] || false);
    }
  }
}

The above function assumes that the execute_func function is declared in the global or window scope. This may not be the ultimate perfect performing solution, but this works. This has a huge scope of optimisation.