javascript - 如果时间等于 x,如何创建一个执行的函数?
问题描述
我正在创建一个网页,我希望获得这方面的帮助。当 UTCHours 和 UTCMinutes 等于特定值时,我需要弹出一个文本。我想要这样的东西。这就像模型,而不是实际代码。
h = utcTime
m = utcminutes
if (h=x and m=y)
{
function myFunction();
}
解决方案
当然,我不会为你做所有事情,但你去吧。一个基地开始。
// 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;
}
我很无聊,所以你去。
// 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;
}
推荐阅读
- svg - 任意背景上粗虚圆阴影线的 SVG 动画
- puppeteer - 我们如何将 Node 的引用传递到 Puppeteer 页面?
- php - Magento 1.7 为什么我的会话混淆了?
- php - Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException 没有消息,当我要更新我的数据库
- javascript - 是否可以从 chrome 扩展中查询 https“安全”站点信息的状态
- c# - 省略视图状态字符串中的连接值
- sql-server - 索引超出了数组 SQL 服务器的范围
- watson-conversation - Watson Conversation 中节点内的上下文大小限制
- reactjs - 在 React-Select 中触发自定义 MenuList 中的传递事件
- excel - MS Excel - 在工作表 1 的整个列中搜索一个值,并将其与工作表 1 中的行值和工作表 2 中的列值进行比较,得到真/假