如何以毫秒为单位测量鼠标移动到页面上?

Pat*_*rns 4 javascript

我如何以毫秒为单位测量鼠标移动到页面上?所以,我希望alert('Message');用户在页面上移动鼠标超过5秒.

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');
    }
};
Run Code Online (Sandbox Code Playgroud)

ade*_*neo 6

你必须做这样的事情,使用油门(我使用300毫秒),然后取消超时等.

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');
    }
};
Run Code Online (Sandbox Code Playgroud)

小提琴


鼠标移动的总时间,原理是相同的,你仍然需要节流,并加上鼠标移动的时间.这在鼠标移动的最后一次之后触发,并且值超过5秒

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");
    }
};
Run Code Online (Sandbox Code Playgroud)

小提琴