views:

39

answers:

1

I'm writing a script for a form-faces xforms product that is keyed off an event built into form faces. The event is called 'xforms-ready'. I have define 'startTime' as happening as soon as the document in 'ready'. What I want the script to do is warn the user that it is taking too long before the 'xforms-ready' happens, say if it's been 6 seconds since 'startTime'. I can easily do things when the 'xforms-ready' event happens using the code below:

new EventListener(document.documentElement,
  "xforms-ready",
  "default",
  function() {
    var endTime = (new Date()).getTime();
  }
);

however the warning will want to happen before 'endTime' is defined. So I guess I want something that works like this:

If 6 seconds has passed since startTime and endTime is not yet defined do X

or possibly more efficiently:

If 6 seconds has passed since startTime and 'xforms-ready' has not yet happened do X

Can anyone suggest a way of doing this?

+1  A: 

You can do this with setTimeout. (Complete example below.) In jQuery's ready handler, set a function to be called in six seconds via setTimeout, and in your xforms ready handler, cancel that via clearTimeout if it hasn't happened yet.

Edit Complete example (rather than my earlier fragmented code snippets), assumes it's okay if your xforms ready handler is within your jQuery ready handler:

jQuery.ready(function() {
    var xformsReadyTimer;

    xformsReadyTimer = setTimeout(function() {
        // Too long, show the warning
        xformsReadyTimer = undefined;
        alert("XForms is taking too long!");
    }, 6000);

    new EventListener(document.documentElement,
      "xforms-ready",
      "default",
      function() {
          if (xformsReadyTimer) {
              // Cancel the warning
              clearTimeout(xformsReadyTimer);
              xformsReadyTimer = undefined;
          }
      }
    );
});

(You might consider making those named functions rather than anonymous ones, but I've used anonymous ones above for simplicity.)

T.J. Crowder
Spot on, thanks
chrism