Interval / setTimeout起始点

时间:2012-07-07 19:21:58

标签: javascript animation loops settimeout

我有几个循环动画(向上/向下),由以下函数定义。

循环间隔

function Cycler(f) {
    if (!(this instanceof Cycler)) {
        // Force new
        return new Cycler(arguments);
    }
    // Unbox args
    if (f instanceof Function) {
        this.fns = Array.prototype.slice.call(arguments);
    } else if (f && f.length) {
        this.fns = Array.prototype.slice.call(f);
    } else {
        throw new Error('Invalid arguments supplied to Cycler constructor.');
    }
    this.pos = 0;
}

Cycler.prototype.start = function (interval) {
    var that = this;
    interval = interval || 1000;
    this.intervalId = setInterval(function () {
        that.fns[that.pos++]();
        that.pos %= that.fns.length;
    }, interval);
}

功能1(向上)

function unpeekTile() {

    var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
    tile1.style.top = "0px";
    tile2.style.top = "0px";

    peekAnimation.execute();
}

功能2(向下)

function peekTile() {

    var peekAnimation = WinJS.UI.Animation.createPeekAnimation([tile1, tile2]);
    tile1.style.top = "-120px";
    tile2.style.top = "-120px";

    peekAnimation.execute();

}

开始

        function c() { Cycler(peekTile, unpeekTile).start(); }
        setTimeout(c, 0);

        function c2() { Cycler(peekTile2, unpeekTile2).start(); }
        setTimeout(c2, 500);

        function c3() { Cycler(peekTile3, unpeekTile3).start(); }
        setTimeout(c3, 2000);

动画现在从1000(间隔时间)+ 0/500/2000(setTimeout)开始,但我希望它们以0,500和2000毫秒开始。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

如果我理解正确,你实际上是在说你希望区间回调不仅要绑定到区间,而且还要在超时结束和设置区间之间执行一次。

这意味着修改Cycler.prototype.start

Cycler.prototype.start = function (interval) {
    var that = this, int_callback;  //<-- added var
    interval = interval || 1000;
    this.intervalId = setInterval(int_callback = function () {
        that.fns[that.pos++]();
        that.pos %= that.fns.length;
    }, interval);
    int_callback(); //<-- added line - call the func immediately, once
}

答案 1 :(得分:0)

一种解决方案是:

Cycler.prototype.start = function (interval,executeImmediately) {
    var that = this;
    interval = interval || 1000;
    var driverFunction = function () {
        that.fns[that.pos++]();
        that.pos %= that.fns.length;
    }
    this.intervalId = setInterval(driverFunction , interval);
    if(executeImmediately) {
        driverFunction();
    }
}

这会将您的功能定义一次,您只需将其输入setInterval并直接调用它。