我正在开发“提醒”应用,我想我完成了,但是我的问题是如何使代码运行或在currentHour
与medicTime
匹配时继续看到数字,警报开始所以我尝试了setInterval
和setTimeout
,但是两者都不适合我(setTimeout不起作用,我必须重新加载页面&setInterval继续发送垃圾邮件),所以我想要一种方法来使代码看到页面中的数据并运行在没有垃圾邮件的情况下发出警报,应用程序也许会每小时提醒用户一次,是的,同时我希望setInterval
的数量少一些,以防页面被错误关闭
// It's my dumb database so yeah do not worry about it
config = {
apiKey: "AIzaSyBZHH97LQ42n7j0fBjKR7LCLXkeDq-L7iw",
authDomain: "pro-core-169202.firebaseapp.com",
databaseURL: "https://pro-core-169202.firebaseio.com",
projectId: "pro-core-169202",
storageBucket: "pro-core-169202.appspot.com",
messagingSenderId: "58388231689"
};
firebase.initializeApp(config);
let dataRef = firebase.database().ref("data");
dataRef.on("child_added", snap => {
let name = snap.child("name").val();
let medicName = snap.child("medicName").val();
let medicTime = snap.child("medicTime").val();
let notes = snap.child("notes").val();
$("#dataShow").append("<tr><td>" + "Name: " + name + "</td><td>" + " -- " + " Medic Name: " + medicName + "</td><td>" + " -- " + " Medic Time: " + medicTime + "</td><td>" + " -- " + " Notes: " + notes + "<br>");
let date = new Date();
let currentHour = date.getHours();
setTimeout(function () {
if (medicTime == currentHour) {
alert("it's " + medicName + " Time!" + "(It's " + medicTime + " Time!)");
}
}, 1)
})
let date = new Date();
let currentHour = date.getHours();
console.log(currentHour);
答案 0 :(得分:0)
日期应在setTimeout回调中检查:
setTimeout(function () {
let date = new Date();
let currentHour = date.getHours();
if (medicTime == currentHour) {
alert("it's " + medicName + " Time!" + "(It's " + medicTime + " Time!)");
}
}, 1)
// This will not work in snippet because sandboxing
$('#test').click(
() => localStorage.setItem('start', new Date().getTime()) // Time in ms from 1 Jan 1970
)
checkTime = () => {
//if no date set in localstorage...
if(!localStorage.getItem('start')) {
clearInterval(myInterval);
}
const currentTime = new Date().getTime();
const startTime = localStorage.getItem('start');
if(currentTime - startTime > 60000){ // if 60s are passed
clearInterval(myInterval); // Unregister interval
alert('Timeout, 60 seconds!');
}
}
// Run the check every seconds
const myInterval = setInterval(checkTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="test">Test</button>