document.onclick settimeout function javascript help
Solution 1
window.twotimer=function(e){
if(arguments[1]!= 'timer'){
// If the 'timer' argument was not passed,
// the function was called from the event,
// so call it again with a timer
e= window.event || e;
var target= e.target || e.srcElement;
setTimeout(function(){return twotimer(target,'timer')},1000);
if(e.stopPropagation) e.stopPropagation();
e.cancelBubble=true;
return false;
}
// if you get to this point, e is the element node clicked
// a second ago-
// put your function body here, using e for the element clicked
alert(e.nodeName+' id='+ e.getAttribute('id')+'\nwas clicked a second ago');
}
document.onclick= twotimer;
Solution 2
Something like:
document.onclick = function () {
setTimeout(check, 1000);
};
- The
setTimeout
method doesn't return a function, it returns a number, which is the timer Id that you can use in case you want to cancel the timer before it fires (withclearTimeout
) - You don't need to use strings as the first argument, use a function reference.
Solution 3
You can make a generic function that will make a delayed event handler. E.g.
// Delay execution of event handler function "f" by "time" ms.
function makeDelayedHandler( f, time)
{
return function( e )
{
var ev = e || window.event;
setTimeout( function()
{
f( ev );
}, time );
};
}
function check( e )
{
// Your original handler
}
document.onclick = makeDelayedHandler( check, 1000 );
Jamex
Updated on June 11, 2022Comments
-
Jamex almost 2 years
I have a document.onclick function that I would like to have a delay. I can't seem to get the syntax right.
my original code is
<script type="text/javascript"> document.onclick=check; function check(e){do something}
I tried the below, but that code is incorrect, the function did not execute and nothing happened.
<script type="text/javascript"> document.onclick=setTimeout("check", 1000); function check(e){do something}
I tried the next set, the function got executed, but no delay.
<script type="text/javascript"> setTimeout(document.onclick=check, 1000); function check(e){do something}
what is the correct syntax for this code.
TIA
Edit:
The solutions were all good, my problem was that I use the function check to obtain the id of the element being clicked on. But after the delay, there is no "memory" of what was being clicked on, so the rest of the function does not get executed. Jimr wrote the short code to preserve clicked event.
The code that is working (not work in IE6)
document.onclick = makeDelayedHandler( check, 1000 ); // Delay execution of event handler function "f" by "time" ms. function makeDelayedHandler( f, time) { return function( e ) { var ev = e || window.event; setTimeout( function() { f( ev ); }, time ); }; } function check(e){ var click = (e && e.target) || (event && event.srcElement); . . .
Thank you all.
update: kennebec's solution works for IE6.