...

View Full Version : call function after idle of ? seconds



maxpouliot
05-24-2006, 04:58 PM
instead of calling a function this way


<input onkeyup="Select(this,'employe');" size="5">

is it possible to call the function after the field has not been changed in 1 or 2 seconds?

Beagle
05-24-2006, 06:07 PM
<input onchange="setTimeout(function(){Select(this,'employe');},2000);" size="5">

not tested, might not work. but you get the idea, I hope.

maxpouliot
05-24-2006, 07:07 PM
<input onchange="setTimeout(function(){Select(this,'employe');},2000);" size="5">

not tested, might not work. but you get the idea, I hope.

Anyone know how come this returns an undefined error?

<input onkeyup="setTimeout(function(){Select(this,'employe')},2000);" size="5">

Beagle
05-24-2006, 08:13 PM
test in Firefox and use their javascript console to get more meaningful errors than the crap IE spews.

digital-ether
05-25-2006, 07:25 AM
<input onkeyup="setTimeout(function(){Select(this,'employe')},2000);" size="5">

What has happened is, the variable "this" no longer refers to the input htmlElement Object when the setTimeout() function is executed after 2 seconds. Instead "this" refers to the "window" object, since setTimeout() is always executed in the scope of the "window".

To preserve the reference to the input Object, you can use the following:


<input onkeyup="var me = this; (function() { setTimeout(function(){Select(me, 'employe')}, 2000); })();" size="5">

This is the form of writing:



<input onkeyup="selectTimeout(this);" size="5">


<script type="text/javascript">
<!--

function selectTimeout(me) {
setTimeout(function(){Select(me, 'employe')}, 2000);
}

function Select(me, var2) {
alert(me);
/* your Select code */
}

//--></script>



withought creating a named function, instead the first one uses anonymous functions.
How both work is that they create a copy of the "this" var, which refers to the htmlElement Input Object, to the "me" var.
The "me" var creates a closure so that the Input Object is available to the Select function later on when its called by setTimeout.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum