Javascript Delayed Hiding of an Element, Delayed Function Calls in Different Contexts

So I'm working on a small "speech bubble" library, and needed to delay hiding of the bubble. It's not that it was required, but it was a pain in the butt figuring out how to arrange the event handlers on the different elements so that you don't end up with a situation where you get a flickering bubble because you hide the bubble, and that fires a mouseover event that, in turn, displays the bubble again. That fires a mouseout event that causes the bubble to be hidden.

The usual right way to fix this is to detect the mouse moving into the area around the hotspot, and when it does that, hide it. My cheap fix is to just delay the hiding, and if the mouse happens to enter another element that requires the bubble to be displayed, the handler for this other element can cancel the hide.

A delay is also "nice" because it also gives the user a chance to roll back if they overshoot a target a little bit.

Here's the code fragment to implement a delay:

  var hide = function () {
    this.bubble.style.display = 'none';
  }
  var delayedHide = function() {
    (function (x) {
      x.hideInProgress = setTimeout(function () {x.hide()},250);
    })(this);
  }
  var cancelHide = function() {
    clearTimeout(this.hideInProgress);
  }

The one really weird part is in delayedHide. What this does is construct a function that will call setTimeout(), then immediately call it. That calls setTimeout(), which registers the timeout handler to fire off in 1/4 second. Why not just call it like this?

this.hideInProgress = setTimeout(function () {this.hide()}, 250);

Well, the problem is that "this" changes between the two calls. When it's called from the bubble object (i.e. b.delayedHide() ), "this" is set to the object. When the timeout happens and the function's called by the system, I think "this" is set to window. Anyway, it's a different "this". "this" may not even exist. We're screwed.

So what we do, instead, is use a function to create a closure. A closure holds is local variables. So, what's happening is that (function(x) { ... })(this) is setting the local variable x to = this. Then, when function(){x.hide()} is created, it also carries the local variable x within the closure. That's because the closure contains the local variables in the scope in which is was defined.

After the call, the outer function wrapper is thrown away, but the inner one is stored away in window, ready to be called in 250 milliseconds.