Jamex Jamex - 1 year ago 174
Javascript Question

document.onclick settimeout function javascript help

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">

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.



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.

Answer Source
    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();
        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;