2012-07-07 46 views
1

我有幾個循環動畫(上/下),它們是由以下函數定義的。Interval/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毫秒開始。任何人都可以幫忙嗎?

回答

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 
} 
+0

我認爲*會將'int_callback'放入全局命名空間。可能想要在那裏拋出一個'var'。 – Dancrumb 2012-07-07 23:10:27

+0

我已經做了 - 見評論(第2行) – Utkanos 2012-07-07 23:15:11

+0

非常感謝 - 爲我解決了!只需稍作更改:int_callback var必須分別聲明:var that = this; var int_callback; – Betsy 2012-07-08 07:04:08

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,還可以直接調用它。