我创建的倒数计时器不起作用。 有趣的是,如果我使用 console.log 打印 count 的值——从 3 开始——会打印类似 -3498 的内容,即使我只打开大约 15 秒,所以设置的间隔一定有问题代码。该值显示(如果计数大于 0),但设置的间隔变化太快。
这是代码。
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);
}
如有任何帮助,我们将不胜感激。
最佳答案
我有点不清楚你想要完成什么,但这里有一个镜头:
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
}
据我所知,您不需要间隔。
关于javascript - 倒数计时器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16762993/