简体   繁体   中英

How can I measure in milliseconds mousemove on the page?

How i can measure in milliseconds mousemove on the page? So, i want alert('Message'); when user move mouse on the page more than 5 seconds.

var showtime = 5000; // milliseconds
var currenttime = 0; // milliseconds

document.onmousemove = function(e){
    // How i can measure time? (increase `currenttime` in milliseconds)
    if(showtime <= currenttime) {
        alert('Message');
    }
};

You'll have to do something like this, using a throttle (I used 300ms), and then canceling the timeout etc.

var showtime = 5000; // milliseconds
var currenttime = 0; // milliseconds
var timer;

document.onmousemove = function(e){
    currenttime = currenttime ? currenttime : Date.now();

    clearTimeout(timer);
    timer = setTimeout(function() {
        currenttime = 0;
    }, 300);

    if ( (Date.now() - currenttime) > showtime) {
        currenttime = 0;
        alert('Message');
    }
};

FIDDLE


For a total time the mouse has been moved, the principle is the same, you'll still have to throttle, and add up the time the mouse moved. This fires after the last the time the mouse moved, and the value exceeds 5 seconds

var showtime  = 5000; // milliseconds
var starttime = 0;    // milliseconds
var totaltime = 0;
var timer;

document.onmousemove = function(e){
    starttime = starttime ? starttime : Date.now();
    clearTimeout(timer);

    timer = setTimeout(function() {
        totaltime += Date.now() - starttime;
        starttime = 0;
    }, 300);

    if (totaltime > showtime) {
        alert("Message");
    }
};

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM