Oct 27, 2008

JavaScript Call SetTimeout or other function with parameters.

I needed to do this few days ago. I struggled to find out how.

Hope this will help to other guys in the same situation (it's so simple that you may never figure it out until someone tell you :D ):


    
var t;
    
function myButtonToTimeOut(id)
     {
        
// We will call the onTimeOut function in a setTimeOut()
        // and will pass the id as a parameter:
        t = setTimeout(function(){onTimeOut(id);}, 2000);
     }
    
function onTimeOut(id)
     {
        alert(
'The caller with ' + id + ' was clicked 2 seconds ago.');
        clearTimeout(t);
     }

what do we do here?
Well, we have a global variable which will hold
the timeOutID (required to clear the timeout).
We have a target function which we want to call in let's say 2 seconds. But we want to pass some parameters to it (for example the sender of the event).

What we do is to create another function (myButtonToTimeOut) in the function body we call the setTimeOut, and pass as parameter a new function which contains our desired call:


function(){onTimeOut(id);}

Voilla. The other things (such as the global variable t) are here only to make this thing work. If you want to test this snippet simply add it to the head of an html page, add few buttons and set their onclick as this one:

onclick="myButtonToTimeOut(this.id);"

When you click on the button, after two seconds you should receive an alert showing you which button was pressed.

Please note: As the code was intended to only show you how to call setTimeOut with parameters, it may have some bugs in it (for example I am not quite sure what will happen if you click two times quickly on the button, or on two diferrent buttons, as t is holding the timeOutId it may get overriden and as a result, some of the alerts may continue to appear).


Have a nice programming!

1 comment:

Павелъ Дончевъ said...
This comment has been removed by the author.