Exit popup + setInterval

715 views Asked by At

I'm trying to create something like Exit Popup but limited to users residing on my page less than 10 seconds. I thought to use setInterval:

var counter = 0;

var myInterval = setInterval(function () {
    // count
    console.log(counter);

    // Clear if more than 10 seconds
    if ( 10 < counter ) {
        console.log('Stop setInterval');
        clearInterval(myInterval);
    }

    ++counter;
}, 1000);

if ( 10 > counter ) {
    // Simplified exit popup function
    $(window).mouseleave(function() {
        console.log('Popup');
        clearInterval(myInterval);
    });

}

First part of code works, but the second part executes even if counter is greater than 10. Why this is not working as it should?

1

There are 1 answers

0
blex On BEST ANSWER

No need for a counter. Just bind the event at page load, and unbind it after X seconds using a setTimeout:

$(window).bind('mouseleave', exitPopup);

setTimeout(function(){
    $(window).unbind('mouseleave', exitPopup);
},10000);

function exitPopup(){
    alert('Exit popup');
}

JS Fiddle Demo (3 seconds)

For this demo, make sure to put your cursor in the lower right window right at the beginning, and wait 3 seconds. It should not appear after that. If you don't wait, it'll show the popup.