Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setTimeout function call with event argument?

What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

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);
}

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

like image 564
C Bauer Avatar asked Nov 30 '10 13:11

C Bauer


1 Answers

Try:

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

EDIT due to OP comments..

To have access to an updated event each time checkPos is fired:

var myNamespace = {};

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

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

timerID = setInterval(checkPos, 500);
like image 196
sje397 Avatar answered Oct 14 '22 08:10

sje397