簡體   English   中英

函數運行時暫停事件

[英]pause event while function runs

我正在編寫一個無限滾動功能,如果$(window).scrollTop()幾乎與文檔高度一樣大,則可以運行它,並且效果很好。

問題在於,新帖子的加載需要花費幾秒鍾的時間,並且在這段時間內,如果頁面已滾動,則在文檔變大之前多次調用了該函數,因此沒有按照我的意圖加載帖子。

我可以在函數中添加一行以暫停特定事件(在這種情況下為scroll事件),直到該函數執行完為止?

function f(){
    //stop $(window).scroll
    //execute code
    //allow $(window).scroll
}
$(window).scroll(function(){
    if(condition){
        f();
    }
});

John Resig前陣子對此發表了文章

這是他使用的代碼

didScroll = false;

$(window).scroll(function() {
     didScroll = true;
 });

setInterval(function() {
    if ( didScroll ) {
      didScroll = false;
      // Check your page position and then
      // Load in more results
   }
}, 250);

您可以使用$.off取消綁定事件,但是我建議僅使用變量來跟蹤事件是否被觸發。

此代碼段將防止在再次將scrolling設置為false之前調用f。

$(window).scroll(function(){
    if(this.scrolling == undefined)
        this.scrolling = false;

    if(this.scrolling == false){
        this.scrolling = true;
        f();
    }
});

function f(){
    //execute code
    window.scrolling = false;
}

您可以在調用滾動事件后將其刪除,如果/在完成發布請求之后/在重新附加它:

function loadPosts() {
    if (condition) { // e.g. scrollTop almost equal to document height.
        $(window).off('scroll', loadPosts);
        $('[selector]').load('[URL-to-posts]', function(posts) {
            bindScroll();
            // Display posts.
        });
    }
}

// Binds the scroll event.
function bindScroll() {
    $(window).on('scroll', loadPosts);
}

$(bindScroll); // Call on document ready.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM