2016-12-27 60 views
-1

我需要设置功能超时的帮助。我试图设置给定的日期和时间超时,但我的转换为毫秒不起作用。基于给定的日期时间设置超时的毫秒数

这是我的代码。请帮忙。

<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

什么是'date'和'time'价值? – philantrovert

+0

日期的值为2016-12-27格式,时间值为15:30格式 –

+0

date = new date(date);该字符串需要转换为日期对象 –

回答

0

你需要使用new Date()解析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); 
+0

感谢您的正确转换格式:) –

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功能。您需要先将其转换为时间对象。注意正确的字符串格式。网上有很好的资源。

更好的办法:

当浏览器重新加载超时被杀害。那很糟。存储时间会更好,并定期检查是否达到时间。这将重新加载生存,死机,关机等:

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"); 
+0

非常感谢您的建议,这真的有帮助 –

+0

如果您发现它有帮助,给一个upvote;) –