JavaScript:根据预定义的时间线自动执行功能

时间:2017-01-01 19:07:25

标签: javascript jquery json function timeline

我正在尝试构建一个Web应用程序,它将根据预定义的时间自动为用户执行JS功能。

例如:我在网页上有以下功能:

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

以及每个用户加载的JSON时间轴:

"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"}
...
]

有没有办法根据它们在时间轴"中显示的顺序和时间自动触发这些功能?

非常感谢您的任何帮助!

1 个答案:

答案 0 :(得分:0)

您的JSON首先出现问题,这是不对的。你可以这样做得更好:

"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"}
  ...
]

注意键间距... ontime之后有一个空格,不应该在那里......

您需要设置一个计时事件处理函数,该函数每秒执行一次:

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);

getFunctionOnTime函数将返回该函数,否则返回false。

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

上述函数假定execute_func函数在全局或window范围内声明。这可能不是最终的完美表现解决方案,但这是有效的。这有很大的优化范围。