-1

我知道这个问题已经出现了很多,相信我我已经尝试了所有的解决方案。我的问题和标题一样简单,clearInterval()功能没有按预期工作。

var newsCheck_handle;
var getNewsTime_handle; 
var originalTitle = document.title; //for title attribute update in newsCHeck function
if (url === 'Home'){
     newsCheck_handle = setInterval(function(){newsCheck(originalTitle)},1000);
     getNewsTime_handle = setInterval(function(){getNewsTime()},120000);
     $("#refreshFeed").on('click', loadNew); //load new news on click
}
else {//stop functions if not on homepage
    clearInterval(newsCheck_handle);
    clearInterval(getNewsTime_handle);
}

我尝试将var's 设置为与间隔相同的级别,而不是之前,但这不起作用。也试过了window.clearInterval()self.setInterval()

以防万一它需要。这是newsCheck功能。它们都发生了相同的效果,并且它们的功能相当相似。

function newsCheck(originalTitle){
var objts = $(".newsItem:first").data("ts");
var objid = $(".newsItem:first").data("id");
var objevent = $(".newsItem:first").data("event");
var ids = $.makeArray(objid); //variable of IDS
var ts = $.makeArray(objts); //variable of ts
var event = $.makeArray(objevent); //variable of ts

if (objts != null && objid != null){
    $.get("../AJAX/get_feed_updates.php",{ ID: ids, ts: ts, event: event },function(result){   
        if (result > 0) {   
            document.title = '(' + result + ') ' + originalTitle;
            if (result == 1){// no plurals
                $("#refreshFeed").html(result + ' more news item.').fadeIn("slow");
            }    
            if (result > 1){ //plurals
                $("#refreshFeed").fadeIn(500).html(result + ' more news items.');
            } 
        }//close if result
    });//close get
}// close if ts
}//close function
4

1 回答 1

0

也许你启动了很多次?因此,您每次都覆盖计时器,并且只清除最后一个。

试试这个,让它开始一次,如果它还没有开始

if (url === 'Home'){
     newsCheck_handle || (newsCheck_handle = setInterval(function(){newsCheck(originalTitle)},1000));
     getNewsTime_handle || (getNewsTime_handle = setInterval(function(){getNewsTime()},120000));
     $("#refreshFeed").on('click', loadNew); //load new news on click
}
else {//stop functions if not on homepage
    clearInterval(newsCheck_handle);
    clearInterval(getNewsTime_handle);
    newsCheck_handle = getNewsTime_handle = undefined;
}
于 2013-06-26T19:12:42.313 回答