[Greasemonkey] Patterns

Edward Lee edilee at gmail.com
Sun Apr 17 04:04:16 EDT 2005


A neat little trick to keep current variable values for later. (Thanks
Tony for the hint)

setTimeout(
(function(dummyVar) { return function() { functionYouWant(dummyVar);
}; }) (varToBeSaved)
, time);

Example:

(function() {
  var i = 0; // set the initial value to 0
  setTimeout((function(x) { // create a function to take the current value of i
    return function() { // return a function for setTimeout to call
      alert(x); // reference x because it gets the value of i
    };
  }) (i), 100); // pass in the current value of i
// setTimeout(function() { alert(i) }, 100); // this code would alert
1 instead of 0 because the closure would have it reference the value
of i 100ms later
  i = 1; // simulate modifying the variable
}) ()

-- 
Ed


More information about the Greasemonkey mailing list