簡體   English   中英

我如何刪除此setTimeout函數

[英]How can i remove this setTimeout function

如果用戶在頁面上處於非活動狀態,則我要啟動一個彈出窗口,但希望在用戶關閉彈出窗口時刪除顯示彈出窗口的功能,因為這很煩人此彈出窗口每隔XX秒打開一次。

這是我用來調用彈出窗口的函數。

<script type="text/javascript">
var timeoutID;

function setup() {
    this.addEventListener("mousemove", resetTimer, false);
    this.addEventListener("mousedown", resetTimer, false);
    this.addEventListener("keypress", resetTimer, false);
    this.addEventListener("DOMMouseScroll", resetTimer, false);
    this.addEventListener("mousewheel", resetTimer, false);
    this.addEventListener("touchmove", resetTimer, false);
    this.addEventListener("MSPointerMove", resetTimer, false);

    startTimer();
}
setup();

function startTimer() {
    // wait 20 seconds before calling goInactive
    timeoutID = window.setTimeout(goInactive, 20000);
}

function resetTimer(e) {
    window.clearTimeout(timeoutID);

    goActive();
}


function goActive() {         
    startTimer();
}

function goInactive() {
    $.magnificPopup.open({
        mainClass: "mfp-fade",
        fixedContentPos: false,
        fixedBgPos: true,
        items: {
            src: "#needtochat"
        },
        removalDelay: 1000, //delay removal by X to allow out-animation
          callbacks: {
            beforeOpen: function() {
               this.st.mainClass = "mfp-3d-unfold";
            },
            close: function() {
                window.clearTimeout(timeoutID); // Thought this may remove the timer function all together?
            }
          },
        type: "inline"}, 0);
}

</script>

您會注意到function goInactive()顯示了模式窗口,並且我有一個回調close:我希望可以清除該函數。

假設close回調如廣告中所述,超時將被清除。 但是,您已附加了幾個事件偵聽器,一旦發生事件,它們將立即重新創建超時。 這里有兩個選擇。

選項1:除了清除計時器之外,還刪除事件偵聽器:

function teardown() {
    this.removeEventListener("mousemove", resetTimer);
    this.removeEventListener("mousedown", resetTimer);
    this.removeEventListener("keypress", resetTimer);
    this.removeEventListener("DOMMouseScroll", resetTimer);
    this.removeEventListener("mousewheel", resetTimer);
    this.removeEventListener("touchmove", resetTimer);
    this.removeEventListener("MSPointerMove", resetTimer);
}

close處理程序中:

close: function() {
    teardown();
    window.clearTimeout(timeoutID);
}

選項2:創建一個標志並使用它來控制計時器的創建:

var popupClosed = false;

function resetTimer(e) {
    window.clearTimeout(timeoutID);
    if (!popupClosed)
        goActive();
}

並在close處理程序中進行設置:

close: function() {
    popupClosed = true;
    window.clearTimeout(timeoutID);
}

據我了解,您可以添加一個變量,例如:

var popupBeenClosed = false;

在“關閉”回調中將其更改為true,並在resetTimer()中添加檢查:

function resetTimer(e) {

    if (!popupBeenClosed) {

        window.clearTimeout(timeoutID);
        goActive();
    }

}

暫無
暫無

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

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