同一时间有多个JavaScript超时

时间:2013-02-22 12:25:43

标签: javascript settimeout setinterval

我正在开发一个HTML5应用程序,我在画布上绘制一系列图像,每个动画之间都有一定的速度和一定的超时。

能够多次使用它我已经为它做了一个功能。

var imgNumber = 0;
var lastImgNumber = 0;
var animationDone = true;

function startUpAnimation(context, imageArray, x, y, timeOut, refreshFreq) {
    if (lastImgNumber == 0) lastImgNumber = imageArray.length-1;

    if (animationDone) {
        animationDone = false;
        setTimeout(playAnimationSequence, timeOut, refreshFreq);
    }
    context.drawImage(imageArray[imgNumber], x, y);
}

function playAnimationSequence(interval) {
    var timer = setInterval(function () {
        if (imgNumber >= lastImgNumber) {
            imgNumber = 0;
            clearInterval(timer);
            animationDone = true;
        } else imgNumber++;
    }, interval);
}

现在在我的主代码中,每次使用正确的参数startUpAnimation时它都可以正常工作。 但是当我想在屏幕上同时绘制多个动画时,每个动画都以不同的间隔和速度绘制它不起作用!

startUpAnimation(context, world.mushrooms, canvas.width / 3, canvas.height - (canvas.height / 5.3), 5000, 300);
startUpAnimation(context, world.clouds, 100, 200, 3000, 100);

现在它会在正确的位置显示两个动画,但它们会在第一个被调用的间隔和超时时生成动画,因此在我的情况下为5000超时和300个间隔。

如何解决这个问题,以便他们独立玩?我想我需要把它变成一个类或者什么,但我不知道如何解决这个问题。在某些情况下,我甚至需要使用此功能同时显示5个动画。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

            var Class = function () {
            this.imgNumber = 0;
            this.lastImgNumber = 0;
            this.animationDone = true;

        }
        Class.prototype.startUpAnimation = function(context, imageArray, x, y, timeOut, refreshFreq) {
            //     if (lastImgNumber == 0) lastImgNumber = imageArray.length-1;

            if (this.animationDone) {
                this.animationDone = false;
                setTimeout(this.playAnimationSequence, timeOut, refreshFreq, this);
            }
            //     context.drawImage(imageArray[imgNumber], x, y);
        };

        Class.prototype.playAnimationSequence = function (interval, object) {
            var that = object; // to avoid flobal this in below function
            var timer = setInterval(function () {
                if (that.imgNumber >= that.lastImgNumber) {
                    that.imgNumber = 0;
                    clearInterval(timer);
                    that.animationDone = true;
                    console.log("xxx"+interval);
                } else that.imgNumber++;
            }, interval);
        };


        var d = new Class();
        var d1 = new Class();
        d.startUpAnimation(null, [], 300, 300, 5000, 50);

        d1.startUpAnimation(null,[], 100, 200, 3000, 60);

它应该有用,

答案 1 :(得分:0)

据我所知,每次调用startUpAnimation都会立即绘制到画布,因为这个执行(你的drawImage(..)调用)还没有被包含在setTimeout或setInterval的回调中。