簡體   English   中英

調試 JavaScript 時序事件

[英]Debugging JavaScript Timing Events

我遇到了這個 JavaScript 腳本的問題。 我已經嘗試了很多方法來讓它工作。 目前那里的警報是出於調試目的,似乎沒有發生。

請幫忙?

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);

謝謝,

將要。

您應該將setTimeout與閉包一起使用,而不是字符串。

var now = new Date().getTime();
setTimeout(function(){
  //your Javascript code here
  //"now" can be used here as a closure
}, 300);

這是一個更安全且獨立的版本。 加載后的 document.write 將完全清除頁面

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);
}

或進行適當的倒計時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);
}

好像在找倒計時?
看到這個小提琴 代碼簡化為:

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);
    }
}

我想代碼可以更簡單地工作。

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);

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM