我需要帮助设置函数的超时。我试图设置给定日期和时间的超时,但我将它们转换为毫秒不起作用。
这是我的代码。请帮忙。
<script>
var ref = firebase.database().ref().child("Message");
var newRef = ref.child("20161227125916539")
newRef.on('value',function(snap){
heading.innerText =snap.child("message").val();
});
ref.on("child_added",function(snap){
var date = snap.child("date").val();
var time = snap.child("time").val();
var type = snap.child("type").val();
var venue = snap.child("venue").val();
var route = snap.child("route").val();
var message = snap.child("message").val();
date = date + time;
date = date.getTime();
var now = new Date();
now = now.getTime();
set = date - now;
var explode = function(){
alert("Boom!");
};
setTimeout(explode, 2000);
});
</script>
答案 0 :(得分:0)
您需要使用date
解析new Date()
。
正如您所说,date
的值为"2016-12-27"
,time
的值为"15:30"
,因此在连接它们时,您还需要一个额外的空间。类似的东西:
date = date + " " + time;
var someDate = new Date(date);
var now = new Date();
var diffInMillis = now - someDate
var explode = function(){
alert ("Boom!");
}
setTimeout(explode, diffInMillis);
答案 1 :(得分:0)
dateobj=new Date(datestring);
timeinmilliseconds=dateobj.getTime();
//by the way, may check the browsers console if sth is not working:
datestring.getTime();// error:undefined function
你在字符串上调用getTime函数。您需要先将其转换为时间obj。请注意正确的字符串格式。网上有很好的资源。
更好的方式:
重新加载浏览器时会终止超时。那很糟。最好存储时间,并定期检查是否到达时间。这将在重装,崩溃,停机等情况下继续存在:
function set(timestring){
localStorage.setItem("timer",new Date(timestring).getTime());//store timer
check();//start checking
}
function check(){
if(var await=localStorage.getItem("timer")){//if timer is set
var now=new Date().getTime()
if(await<=now){//time reached, or reached in the past
alert("Yay, timer finished");
}else{//not reached yet
console.log(await-now+" left");//log the time left
setTimeout(check,1000);//check again in a scond
}}
window.onload=check;// browser started, check for an existing timer
像这样使用:
set("28-12-2016 12:30");