当我的秒表使用setInterval更新时,它会闪烁,如何使其平滑?

时间:2018-01-01 18:51:35

标签: javascript html5 setinterval stopwatch

您好我在javascript中制作了一个秒表,每次更新时,都会删除,然后再次显示并删除。所以它每秒出现并消失,使它眨眼。如何让它出现,直到下一次更新,平稳过渡。

这是我的代码:

function GameTimer() {
  var gameTimeMinutes = 0;
  var gameTimeSeconds = 0;
  var gameTime = "";

  this.addTime = function() {
    gameTimeSeconds += 1;
    if (gameTimeSeconds < 10) {
      gameTime = gameTimeMinutes + " : 0" + gameTimeSeconds;
    } else {
      gameTime = gameTimeMinutes + " : " + gameTimeSeconds;
    }

    if (gameTimeSeconds == 60) {
      gameTimeSeconds = 0;
      gameTimeMinutes++;
    }
  };

  this.draw = function() {
    graph.clearRect(0, 0, canvas.width, canvas.height);
    var fontSize = 25;
    graph.lineWidth = playerConfig.textBorderSize;
    graph.fillStyle = playerConfig.textColor;
    graph.strokeStyle = playerConfig.textBorder;
    graph.miterLimit = 1;
    graph.lineJoin = 'round';
    graph.textAlign = 'right';
    graph.textBaseline = 'middle';
    graph.font = 'bold ' + fontSize + 'px sans-serif';
    graph.strokeText(gameTime, 100, 30);
    graph.fillText(gameTime, 100, 30);
  };

  this.update = function() {
    this.addTime();
    this.draw();
  }.bind(this);

  this.update();
}

var playerConfig = {textBorderSize: "1px", textColor: "black", textBorder: "solid"};
var canvas = document.getElementById("timer");
var graph = canvas.getContext("2d");
var gameTimer = new GameTimer();
setInterval(gameTimer.update, 1000);
<canvas id="timer" width="200" height="100"></canvas>

所以只是为了澄清,我尝试将间隔时间改为十秒,并且它每十秒出现并消失,这意味着它会在接下来的十秒内消失,直到它出现并再次消失。它不会留在那里,直到下次更新。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为闪烁可能是因为setInterval没有与屏幕刷新率同步。如果是这样,requestAnimationFrame可以解决这个问题。

这确实使用了不必要的系统资源,但无论如何都可以解决您的问题。

试试这个:

this.timeUntilUpdate = Date.now();
this.update = function(){
    if(Date.now() - this.timeUntilUpdate > 1000){
        this.addTime();
        this.draw();
    }
    requestAnimationFrame(this.update);
}

最后将setInterval(gameTimer.update, 1000);替换为requestAnimationFrame(GameTimer.update)或仅GameTimer.update();