用事件参数调用Javascript setTimeout函数?

C B*_*uer 9 javascript jquery settimeout

使用setTimeout时拉入事件对象的最佳方法是什么?我正在使用jQuery来处理所有浏览器中事件模型的规范化,但我不确定如何将'e'对象放入checkPos函数中.

我目前的代码:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}
Run Code Online (Sandbox Code Playgroud)

目前该代码工作一次,因为该函数在mousedown事件中被调用,但在用户移动鼠标时从不更新e对象.FF javascript错误控制台还声明它是'一个无用的setTimeout调用(在参数周围缺少引号?)',但是遵循该建议会导致它完全失败.

如何从setTimeout调用中提取'e'事件参数?

编辑:在每500ms重新运行checkPos函数的代码中添加

sje*_*397 10

尝试:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(function(){checkPos(e);}, 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
}
Run Code Online (Sandbox Code Playgroud)

由OP评论编辑..

要在每次触发checkPos时访问更新的事件:

var myNamespace = {};

$('body').mousemove(function(e) {
    myNamespace.mouseEvent = e; 
});

function checkPos() {
    doSomethingWith(myNamespace.mouseEvent);
}

timerID = setInterval(checkPos, 500);
Run Code Online (Sandbox Code Playgroud)


Oll*_*rds 7

首先,为什么你使用两个超时?在我看来,setInterval()会更好

function MouseDownEvent(e) {
 *snip*
 clearInterval(intervalID);
 intervalID = setInterval(function(){checkPos(e);}, 500);
}
Run Code Online (Sandbox Code Playgroud)

其次,请你澄清一下:"......但是当用户移动鼠标时,永远不会更新电子对象." 为什么用户移动鼠标时会更新事件对象?您只分配了一个mouseDown处理程序.如果你想在每次鼠标移动时做一些事情,那么你应该使用mouseMove事件,在这种情况下,无论如何都不需要超时/间隔.

function MouseMoveEvent(e) {
 //called every time the mouse is moved, event object will contain position
}
Run Code Online (Sandbox Code Playgroud)

与JavaScript一样,您应首先寻找事件驱动的解决方案,并且只在必要时才使用定时处理程序.

*编辑 - 解决评论中提出的问题*

var handler = {
    i : 0,
    function : mouseMoveEvent(e) {
      handler.i++;
      if (handler.i % 100 == 0) {
        //Do expensive operations
      }
    }
}

$(myElement).bind("mousemove", handler.mouseMoveEvent);
Run Code Online (Sandbox Code Playgroud)