[英]Debugging JavaScript Timing Events
I'm having a problem with this JavaScript script.我遇到了这个 JavaScript 脚本的问题。 I've tried a number of things to get it to work.
我已经尝试了很多方法来让它工作。 The alerts in there at current are there for debugging purposes, and seem to be failing to occur.
目前那里的警报是出于调试目的,似乎没有发生。
Help please?请帮忙?
function checkTime(this_time){
var the_string = "checkTime("+this_time+")";
var now = ((new Date()).getTime());
if(parseInt(now) >= parseInt(this_time)){
document.write("TIMEUP!");
}
alert(now);
alert(this_time);
var t = setTimeout(the_string,300);
}
var the_time = (((new Date()).getTime())+19000);
var the_string = "checkTime("+the_time+")";
var t = setTimeout(the_string,300);
Thanks,谢谢,
Will.将要。
You should use setTimeout
with closures instead of strings.您应该将
setTimeout
与闭包一起使用,而不是字符串。
var now = new Date().getTime();
setTimeout(function(){
//your Javascript code here
//"now" can be used here as a closure
}, 300);
Here is a safer and self-contained version.这是一个更安全且独立的版本。 A document.write after load will clear the page completely
加载后的 document.write 将完全清除页面
http://jsfiddle.net/mplungjan/Zt5k7/ http://jsfiddle.net/mplungjan/Zt5k7/
window.onload=function() {
var timer = function (endTime) {
var end = new Date(endTime);
var tId;
this.checkTime=function(){
var now = new Date();
document.getElementById("msg").innerHTML=now.toLocaleString();
if (now.getTime()>=end.getTime()) {
document.getElementById("msg").innerHTML="TIME's UP!";
clearInterval(tId);
}
}
tId = setInterval(this.checkTime,300);
}(new Date().getTime()+5000);
}
or for a proper countdown http://jsfiddle.net/mplungjan/Zt5k7/1/或进行适当的倒计时http://jsfiddle.net/mplungjan/Zt5k7/1/
window.onload=function() {
var timer = function (endTime) {
var end = new Date(endTime);
var tId;
this.checkTime=function(){
var now = new Date();
document.getElementById("msg").innerHTML=now.toLocaleString();
var diff = end.getTime()-now.getTime()
if (diff >= 1) document.getElementById("msg").innerHTML=parseInt(diff/1000)+1;
else {
document.getElementById("msg").innerHTML="TIME's UP!";
clearInterval(tId);
}
}
tId = setInterval(this.checkTime,300);
}(new Date().getTime()+9000);
}
Seems like you're looking for a countdown?好像在找倒计时?
See this fiddle .看到这个小提琴。 The code is simplified to:
代码简化为:
var bench = 19000 + new Date().getTime(),
timer = setInterval(
function(){
checkTime(bench);
}
, 1000
);
function checkTime(this_time){
var check = new Date - this_time;
if(check>=0){
alert('time\'s up!');
clearInterval(timer);
}
}
I suppose the code could be made more simple to work.我想代码可以更简单地工作。
function checkTime(this_time){
var now = ((new Date()).getTime());
if((now - this_time) >= 0){
document.write("TIMEUP!");
window.clearInterval(timer);
}
}
var t_t = (((new Date()).getTime())+19000);
var timer = window.setInterval(function(){
checkTime(t_t); }
, 300);
Cheers!干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.