PDA

View Full Version : setTimeout - is this right / legal?



Krupski
Oct 25th, 2011, 04:27 AM
Hi all,

I've noticed that setTimeout seems to return a simple integer as it's "id" which can be used to clear the timeout ahead of time.

So, in order to have multiple setTimeouts called (which requires the previous one to be cleared before the next one is called), I simply did this:



clearTimeout(setTimeout(function() {
/* some code */
}, 1000) -1);
Note the "-1"... each time this code is called, it starts a new setTimeout and clears "instance-1" which is supposed to be the previous instance.

The idea is that this block can be called hundreds of times, and when the calling finally stops, the inner code is executed 1 second later.

This SEEMS to be working (yes, even in MSIE!). Question is, am I fooling myself? Is this wrong?

If so, what's the right way to do it?

Thanks...

-- Roger

(btw, the actual use of this is dynamic resizing of a DIV by dragging the corner with the mouse.... I want the actual PX size to display live while resizing, then after resizing stops, the size display goes away 1 second later... in case you were wondering).

Old Pedant
Oct 25th, 2011, 05:10 AM
It may work, but there's nothing in the spec that says it has to.

What's wrong with:



var myTimeout = null;

function replaceTimeout( f, t )
{
clearTimeout(myTimeout);
setTimeout( f, t );
}

....
replaceTimeout(
function() {
/* some code */
}, 1000);


Just to be safe?

mrhoo
Oct 25th, 2011, 07:32 AM
You only need to clearTimeout if you want to abort a timeout before it runs.

Logic Ali
Oct 25th, 2011, 12:23 PM
Presumably the ident returned will always be sequential, but this can only work reliably if there are no other timed processes going on concurrently.

You could create a closure to save the correct value, then just call the returned function at will:

<!DOCTYPE HTML>
<html>
<head>
<title>Timeout Reset</title>
</head>
<body>
<script type="text/javascript">

function resetTimer( funcRef, period )
{
var timerIdent = 0;

return function()
{
clearTimeout( timerIdent );

timerIdent = setTimeout( funcRef, period );
}
}

function myFunc(){ document.title = n++ }

var n = 1,
f = resetTimer( myFunc, 2000 );

f(); f(); f(); f(); f(); f(); f(); f(); f(); /* Only last call executes myFunc */

</script>

</body>
</html>

Krupski
Oct 25th, 2011, 03:06 PM
Presumably the ident returned will always be sequential, but this can only work reliably if there are no other timed processes going on concurrently.

You could create a closure to save the correct value, then just call the returned function at will:


YES! I never thought of that. Another setTimeout could very well run at the same time. Using a closure is the right way to do it. Thanks!

-- Roger