2012-12-21 54 views
0

我製作了一段時間間隔的動畫。這是我的腳本:clearinterval with javascript

var count = 0; 
var countSecond = -40; 
function arrowAnimation() { 
    if (count > 40) { 
     clearInterval(); 
    } 
    $('.list-what-we-do .arrow').css({ 
     top: (count++) + 'px' 
    }); 
} 
function arrowAnimationSecond() { 
    if (countSecond > 0) { 
     clearInterval(); 
    } 
    $('.list-what-we-do .arrow').css({ 
     right: (countSecond++) + 'px' 
    }); 
} 

setInterval(arrowAnimation, 5); 
setInterval(arrowAnimationSecond, 5); 

現在我的問題。我怎樣才能停止間隔。我用clearInterval。但那不起作用。我怎樣才能解決這個問題?感謝您的幫助!

+1

你沒有捕獲從設定的時間間隔返回值和用它作爲清晰間隔的論據。 – ryadavilli

回答

5

當您使用setIntervalsetTimeout返回值是一個引用;您將此參考傳遞給clearInterval以取消。

var foo = setTimeout(...); 
clearTimeout(foo); 
0

您必須將setInterval方法的返回值賦值給一個變量

然後你就可以在以後清除它使用clearInterval

var count = 0; 
var countSecond = -40; 

var interval = setInterval(arrowAnimation, 5); 
var secondInterval = setInterval(arrowAnimationSecond, 5); 

function arrowAnimation() { 
    if (count > 40) { 
     clearInterval(interval); 
    } 
    $('.list-what-we-do .arrow').css({ 
     top: (count++) + 'px' 
    }); 
} 
function arrowAnimationSecond() { 
    if (countSecond > 0) { 
     clearInterval(secondInterval); 
    } 
    $('.list-what-we-do .arrow').css({ 
     right: (countSecond++) + 'px' 
    }); 
} 
相關問題