如何停止或暂停此程序?

时间:2016-01-14 21:05:26

标签: javascript settimeout cleartimeout

我尝试使用clearTimeout,但失败了,有人能告诉我如何停止或暂停这个动画吗?以下是我的javascript代码:

window.requestAnimFrame = (function(callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

function drawRectangle(myRectangle, context) {
    context.beginPath();
    context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = myRectangle.borderWidth;
    context.strokeStyle = 'black';
    context.stroke();
}

function myFunction() {
   var m = document.getElementById("myRange").value;
   document.getElementById("demo").innerHTML = m;
}

function animate(myRectangle, canvas, context, startTime) {

    var time = (new Date()).getTime() - startTime;
    var m = document.getElementById("myRange").value;
    myRectangle.y = 380 - m * Math.cos(time * Math.PI / 2000);
    context.clearRect(0, 0, canvas.width, canvas.height); 
    drawRectangle(myRectangle, context);

   requestAnimFrame(function() {
      animate(myRectangle, canvas, context, startTime);
    });
}

var myRectangle = {
    x: 150,
    y: 150,
    width: 50,
    height: 50,
    borderWidth: 4
};

drawRectangle(myRectangle, context);

setTimeout(function() {
    var startTime = (new Date()).getTime();
    animate(myRectangle, canvas, context, startTime);
}, 0);

3 个答案:

答案 0 :(得分:2)

您的回调应该停止调用requestAnimationFrame

var stop = false;
function stopAnimation() {
    stop = true;
}

function animate(myRectangle, canvas, context, startTime) {

    // ...

    if (stop) {
        stop = false;
    }
    else {
        requestAnimFrame(function() {
            animate(myRectangle, canvas, context, startTime);
        });
    }
}

答案 1 :(得分:0)

我想说最简单的方法是将超时存储在稍后可以清除的变量中,例如

var myTimeout = 0;
window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function (callback) {
            myTimeout = window.setTimeout(callback, 1000 / 60);
    };
})();

...

function stopAnimation () {
  if (myTimeout) {
    clearTimeout(myTimeout);
  }
}

答案 2 :(得分:-1)

设置时,请尝试保存Timeout的ID:

var timeoutId = window.setTimeout(...);

然后,要停止动画,它应该像使用id:

清除超时一样简单
function stopAnimation(timeoutId) {
  window.clearTimeout(timeoutId);
}