如何删除此setTimeout函数

时间:2015-04-07 12:17:01

标签: javascript jquery

如果用户在页面上处于非活动状态但我希望在用户关闭弹出窗口时显示弹出窗口的功能,则启动弹出窗口,因为这只是令人讨厌的每个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:,我希望能够清除该功能。

2 个答案:

答案 0 :(得分:1)

假设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);
}

答案 1 :(得分:0)

据我了解,您可以添加变量,例如:

var popupBeenClosed = false;

在&#34;关闭&#34;中将其更改为true回调,并在resetTimer()中添加一个检查:

function resetTimer(e) {

    if (!popupBeenClosed) {

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

}