0

I have this detector script in order to detect if user/mouse is leaving from the page (exit trap). Its working well except script is too fast, sometimes it detects when mouse is initially coming into page from the adress bar. How to delay it for 30 seconds so that check is done only if user has stayed 30 secs on page?

jQuery(document).ready(function($) {
jQuery(document).setTimeout(function(f) {           
jQuery(document).mousemove(function(e) {    
if (e.pageY - jQuery(document).scrollTop() <= 7)
if ( document.referrer == null  {        USER LEAVING !!! }
});
, 2000);
});

Tom
  • 6,725
  • 24
  • 95
  • 159

2 Answers2

0

The simplest way I can think of is to grab a timestamp when the page loads, then check it every time mousemove fires.

Basically:

var movementThreshold = 0;
$(document).ready(function () {
    movementThreshold = new Date().getTime() + 30000; // Get the current time, add 30s
});
$(document).mousemove(function (e) {
    if (new Date().getTime() > movementThreshold) {
        // process the event, at least 30s has passed
    }
});
ssube
  • 47,010
  • 7
  • 103
  • 140
0

I have rewritten your code below to fix some of the syntax errors and function problems

A few tips

  • Use $ not jQuery unless there is a specific reason otherwise. Its shorter and more concise.
  • setTimeout is not a jQuery method, please see the docs here.
  • Why are you even trying to stop the user from leaving? This is bad UX unless you are specifically trying to help the user not lose unsaved data.
  • Your check is broken to detect if a user is leaving a page, I would suggest searching for something like this.

$(function($) {
    setTimeout(function() {
        $('body').mousemove(function(e) {    
            if (
                (e.pageY - jQuery(document).scrollTop() <= 7) &&
                (document.referrer == null)
            ) {
                // handle
            }
        });    
    }, 30000);
});
Community
  • 1
  • 1
Undefined
  • 11,234
  • 5
  • 37
  • 62