PDA

View Full Version : Script execution management: setTimeoutOnce.js


Alex Vincent
09-13-2004, 12:09 AM
The actual script is here (http://www.mozdev.org/source/browse/abacus/content/abacus/content/tools/setTimeoutOnce.js?rev=1.1&content-type=text/plain). The explanation is here (http://weblogs.mozillazine.org/weirdal/archives/006443.html).

Think of saving processor time and not doing DOM calls more often than necessary...

liorean
09-13-2004, 12:37 AM
Isn't it easier (or at least shorter) to do that like this?function callOnce(fn){
var
ran=false;
return function(){
return ran?
null:
fn.apply(this,arguments);
}
}

var canOnlyRunOnce= callOnce(functionThatShouldOnlyBeCalledOnce);

// And then in the timeouts you do

setTimeOut(canOnlyRunOnce,time);

// as many times as you like, the functionThatShouldOnlyBeCalledOnce will
// never be run again by calling canOnlyRunOnceOr did I miss some feature in that?

Alex Vincent
09-14-2004, 09:53 PM
I'm not sure I follow you, liorean. Look at my scenario of A() calling B() and C(), and B() and C() each call D(). Can you explain this to me in those terms?

The "var canOnlyRunOnce" bit doesn't really solve the problem, as that declares a local variable (meaning if B() had "var canOnlyRunOnce", then C() will have another "var canOnlyRunOnce", and one way or another you've got a bug). You also don't want to set a global variable, because global variables are usually not a good idea, at least for object-oriented purposes and being able to update/maintain the code.

liorean
09-14-2004, 10:54 PM
Well, there it technically no real difference between declaring a global function as you did, and declaring a global variable with a function value as I did. But if you wish you can always rerig it to create a member on the callOnce object, or perhaps the D object instead. How I meant it to be used was that instead of calling D inside each of A, B and C, you would call E, where E is previously assigned the return value of callOnce(D).

Come to think of it, my solution lacks one detail: You can only call D through E once and never again, but I guess you want to be able to call it more than once but never simultaneously from many.

Alex Vincent
09-15-2004, 05:52 AM
Bingo. :cool: Do you think my name for the function is inappropriate, given the debate you and I had over it?

(Also, I'm wondering why I didn't include a clearTimeoutOnce() function!)

liorean
09-15-2004, 10:55 AM
Well, SimultaneuslyExclusive seems to me like a more appropriate naming than Once, but unless you want an overlong name I think yours would be just fine.