首页 > 解决方案 > 如果时间等于 x,如何创建一个执行的函数?

问题描述

我正在创建一个网页,我希望获得这方面的帮助。当 UTCHours 和 UTCMinutes 等于特定值时,我需要弹出一个文本。我想要这样的东西。这就像模型,而不是实际代码。

h = utcTime
m = utcminutes
if (h=x and m=y) 
   {
    function myFunction();
}

标签: javascripthtmldatetime

解决方案


当然,我不会为你做所有事情,但你去吧。一个基地开始。

// The button functionality
const $ = (x) => document.getElementById(x);

$('start').addEventListener('click', ()=>{
    startTime();
});

$('stop').addEventListener('click', ()=>{
    stopTime();
});

// The timer

// set variables
let date,
start,
stop;

function startTime() {
  date = new Date(); // get current date.
  start = date.getTime(); // get time from current date
  // Just output
  document.getElementById("showStart").innerHTML = start;
}

function stopTime() {
  date = new Date(); // get current date.
  stop = date.getTime(); // get time from current date
  // just output
  document.getElementById("showStop").innerHTML = stop;
  document.getElementById("difference").innerHTML = stop-start;
}

jsfiddle

我很无聊,所以你去。

// The button functionality
const $ = (x) => document.getElementById(x);

$('setAlert').addEventListener('click', ()=>{
    setAlert(3); // alert in x seconds.
});

// set variables
let date,
target,
stop,
interval = 1; // integer.

function setAlert(time) {
  date = new Date(); // get current date.
  target = date.getTime() + ( (time * 1000) - ((interval * 1000) +1000) ); // sets the time it should alert.
  /*
   * time -1 because it's a 1s interval, that means when it reaches x = y it will alert 1s later by the next "check". This why you need to subtract 1s.
   * (time-1)*1000 is because the getTime returns time in ms not in seconds. You would need to make it setAlert(3000),
   *         i made it bit easier by multiplying the value by 1000 = ms.
   */
  // The loop that checks time
  setInterval(function(){ // This function makes the "checking each X ms"
      if(stop !== target){ // Check if time was reached.
          stopTime(); // Check time
      }else{
          alert("TIME IS OVER"); // When time is reached do this.
      }
  }, interval*1000); // Refreshes the time each second.

  // Just output
  document.getElementById("showTarget").innerHTML = target+(interval*1000); // Because the target time has "minus" in it (line 16) it needs to be added to show the real target time.
}


function stopTime() {
  date = new Date(); // get current date.
  stop = date.getTime(); // get time from current date
  // just output
  document.getElementById("showStop").innerHTML = stop;
  // document.getElementById("difference").innerHTML = stop-target;
}

jsfiddle v2


推荐阅读