2014-01-27 97 views
0

我有一個使用SwipeJS構建的圖像旋轉木馬,在從縱向 - >橫向或橫向 - >縱向更改方向時,我會銷燬並重建。更改方向時無法清除時間間隔或超時

我有一個問題,我似乎無法用下面的代碼清除間隔/超時。正如我所看到的那樣,console.log(now)從每5秒被調用一次(如預期)到每2.5秒被調用一次。大概這是因爲最初的setInterval功能仍然有效。

我該如何清除/殺死它,以便在任何時候只有一個間隔工作?

我正在使用jQuery Mobile 1.3.1。

if ($.event.special.orientationchange.orientation() === 'portrait') { 
    // Portrait mode 

    clearTimeout(slideshowHandle); 

    // ...trash the old slider, then build a new one... 
} else { 
    // Landscape mode 

    clearTimeout(slideshowHandle); 

    // ...trash the old slider, then build a new one... 
} 

// call the SwipeJS next method every 5 seconds to move to the next slide in the carousel 
var slideshowHandle = setInterval(function() { 

    // just some code for debugging purposes 
    var now = new Date(), 
    now = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds(); 
    console.log(now); 

    // trigger a swipe 'next' 
    container.Swipe('next'); 

}, 5000); 
+0

收聽'orientationchange'事件。 '$(document).on(「orientationchange」,function(e){if(e.orientation =「portrait」){// code}});' – Omar

+0

@Omar方向更改檢測代碼正常工作,其他事情正在進行,如顯示特定於景觀的內容,並且所有工作都正常。我認爲這個問題更多的是我的'setInterval'實現。 – crmpicco

回答

1

我必須有一個範圍問題,因爲它連接到window做的伎倆(也變回clearInterval) :

// clear the interval on the slideshow 'next' (if we have it) when changing orientation 
if (window.slideshowHandle) { 
    window.clearInterval(window.slideshowHandle); 
} 

// call the SwipeJS next method every 5 seconds to move to the next slide in the carousel 
window.slideshowHandle = window.setInterval(function() { 
    swipeContainer.Swipe('next'); 
}, 5000); 
+1

哈,很好。我們無法看到沒有整個代碼庫的情況,但我很高興您能在我的幫助和自己的幫助下找到答案。 – drinchev

+0

@drinchev感謝您的幫助。 – crmpicco