1

On page load I setup some functions and call the first one which is supposed to go through step by step.

after5Seconds();

function after5Seconds() {
  setTimeout(hideOne, 5000);
}
function hideOne() {
  $('.toggleme#one').fadeOut(showTwo);
}
function showTwo() {
  $('.toggleme#two').fadeIn('125', 'swing', startAllOver); 
}

I'm finding that often some callbacks get stalled and fail silently and i'm starting to update each to be more like:

  • setTimeout to trigger the callback in N milliseconds if it hasn't already been triggered

Something like:

  function wrapMeInDelay(fn, timer) {
    var hasBeenCalled = false;
    var ctx = function() {
      if (hasBeenCalled) {
        return false;
      } else {
        hasBeenCalled = true;
        return fn();
      }
    };
    setTimeout(ctx, timer);
    return ctx;
  }

basically I want to start adding timeouts to the callbacks to make sure they are called if the jquery/whatever callback doesn't trigger it first.

Is there another more common way of doing this i'm not aware of?

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114
  • I think perhaps you are looking for [`.queue`](https://api.jquery.com/queue/)? Or, since it is over several elements, maybe checkout leveraging [`.when()` and `.done()`](https://stackoverflow.com/questions/18499000/using-jquery-queue-with-multiple-element-animations). – Alexander Nied Mar 27 '18 at 18:59
  • i think you're missing my point. That sometimes the object meant to call the callback fails to for one reason or another. I'd like to add a timeout of sorts so the callback triggers by either the timeout or the caller – Blair Anderson Mar 27 '18 at 19:02
  • OK, I see, my mistake. So if it is failing silently you couldn't leverage one of the deferred error handlers like [`.fail()`](https://api.jquery.com/deferred.fail/), right? Have you explored at all why it is failing silently? Resolving that might be more of a root cause solution, where as the pattern you are using more treats the symptom. Not to say that it is incorrect, as I'm not aware of the full context of the problem you're facing-- I'm just speculating. – Alexander Nied Mar 27 '18 at 19:07

1 Answers1

0

If I understand you correctly, you want to call some function after X seconds only if this function is not already called?

var _timeout;
function onTrigger(){
  if (_timeout){
    clearTimeout(_timeout);
  };
  console.log("function triggered");
};
_timeout = setTimeout(onTrigger, 5000);
onTrigger();

You need to store in variable reference to that timeout, and when function is called, remove that timeout (clearTimeout). In that case timeout will not be executed.

stolex
  • 78
  • 5