2015-04-02 110 views
0

我在我的頁面上創建一個小股票,以編程方式向用戶顯示說明。我已經很好地工作了:如何覆蓋requestAnimationFrame循環?

var ticker = document.getElementById('ticker'); 

function instruct (message) { 
    var message = message; 
    var letters = message.split(''); 
    var part = ''; 

    function animate() { 
    if (letters.length !== 0) { 
     ticker.textContent = ''; 
     part += letters.shift(); 
     ticker.textContent = part; 
     return requestAnimationFrame(animate); 
    } 
    } 
    animate(); 
} 

這很可愛,它看起來像是很快輸入消息給用戶。

所以這裏有幾個樣本消息:

同時
instruct('Great, thanks!'); 
instruct('What\'s next?'); 

一個信息工作得很好,但是當兩者發生一次,時間越長一個勝出。我需要第二個來取消或覆蓋任何仍在運行的東西。

不知道如何清潔乾淨。

任何幫助將搖滾!

回答

1

cancelAnimationFrame - 就像clearInterval

var ticker = document.getElementById('ticker'); 
 
var animFrame; 
 
function instruct (message) { 
 
    var message = message; 
 
    var letters = message.split(''); 
 
    var part = ''; 
 
    
 
    cancelAnimationFrame(animFrame); 
 

 
    function animate() { 
 
    if (letters.length !== 0) { 
 
     ticker.textContent = ''; 
 
     part += letters.shift(); 
 
     ticker.textContent = part; 
 
     return requestAnimationFrame(animate); 
 
    } 
 
    } 
 
    animFrame = animate(); 
 
} 
 

 

 
setTimeout(function() { instruct('this is a testing message'); },500); 
 
setTimeout(function() { instruct('this is a second testing message'); },600);
<div id="ticker"></div>

+0

輝煌!非常感謝 : ) – Costa 2015-04-02 17:50:05