1

The countdown timer I created doesn't work. Interestingly, if I use console.log to print the value of count--which starts at 3--something like -3498 is printed, even if I am only on for around 15 seconds, so there must be something wrong with the set interval code. The value is displayed(if count is greater than 0), but set interval changes too quickly.

Here's the code.

function countdown(){
  window_width=window.innerWidth-70;
  window_height=window.innerHeight-150;

  canvas = document.getElementById("gameCanvas");
  ctx=canvas.getContext("2d");
  canvas.width  = window_width;
  canvas.height=window_height;

  if(count>0){
    ctx.font = '40pt Calibri';
    ctx.fillStyle = "white";
    ctx.fillText(count, window_width/3, window_height/2);
  }
  else if(count===0){
    ctx.fillText("Go!", window_width/3, window_height/2);
  }
  else{
   return;
  }

  setInterval(function(){count=count-1},1000);
  requestAnimationFrame(countdown);
}

Any help would be appreciated.

4

2 回答 2

1

显示值,但变化太快

您将需要区分逻辑和表示。当countdown函数被调用时,你安排一个函数以 1 秒为单位减少计数,同时你安排countdown尽可能快地再次调用。画布的更新间隔大约是 16 毫秒……这意味着画布count以该速率减少,仅在启动后延迟 1 秒。

更糟糕的是,正如您使用的那样setInterval,它永远重复减少count,而该过程在每个动画帧都开始......</p>

解决方案是根本不使用setTimeout/ setInterval。它们不可靠,不应用于测量时间。相反,从Date对象获取准确的时间戳(每次您需要它们时,即每个动画帧):

var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
canvas.width  = window.innerWidth -70;
canvas.height = window.innerHeight-150;
ctx.font = '40pt Calibri';
ctx.fillStyle = "white";

var count = …;

var estimatedEnd = Date.now() + count*1000;

function countdown(){
    var currentCount = (estimatedEnd - Date.now()) / 1000;

    if (currentCount>0){
        ctx.fillText(currentCount, window_width/3, window_height/2);
        requestAnimationFrame(countdown);
    } else if (currentCount===0){
        ctx.fillText("Go!", window_width/3, window_height/2);
    }
}
countdown();
于 2013-05-26T20:46:01.527 回答
1

我有点不清楚你想要完成什么,但这里有一个镜头:

window.count = 3;

setTimeout(countdown,1000);

function countdown(){
  window_width=window.innerWidth-70;
  window_height=window.innerHeight-150;

  canvas = document.getElementById("gameCanvas");
  ctx=canvas.getContext("2d");
  canvas.width  = window_width;
  canvas.height=window_height;

  count--;

  if(count>0){
    ctx.font = '40pt Calibri';
    ctx.fillStyle = "white";
    ctx.fillText(count, window_width/3, window_height/2);
    setTimeout(countdown,1000);
  }
  else if(count===0){
    ctx.fillText("Go!", window_width/3, window_height/2);
  }
  else{
   return;
  }

  requestAnimationFrame(countdown); // not sure if this is needed
}

据我所知,您不需要间隔。

于 2013-05-26T20:02:32.037 回答