0

Is it possible to wrap functions like setTimeout and then fire callback. Like in jQuery $(selector).on('action', callback).

var obj = {
   mth1: function (callback) {
       //----need to wrap to something
          setTimeout(function () { console.log("1"); }, 1000);
          console.log('2');
       //----
       // callback;
   }
};
function callback() {
   console.log('3');
};
(function () { obj.mth1(callback); }) ();

What I need:

2
1
3
2
  • Is there any reason you can't simply run callback() after console.log(1) in the setTimeout function? Commented Feb 28, 2012 at 14:24
  • That is specific case, below i wrote another situations, i can repost: But imagine that will be another code instead of setTimeout, which will return pdf or error message (if fail on generating pdf). So i need to wait while response will come back and if response is OK - than call downloading dialog, else if response return 500 - show error message in label. I can`t figure it out how to call downloading dialog if pdf returned from ajax. Commented Feb 29, 2012 at 12:14

2 Answers 2

2

Simply add it at the end of your function inside the setTimout

// *snip*
setTimeout(function () { 
    console.log("1");
    callback();
}, 1000);
// *snip*
Sign up to request clarification or add additional context in comments.

1 Comment

But imagine that will be another code instead of setTimeout, which will return pdf or error message (if fail on generating pdf). So i need to wait while response will come back and if response is OK - than call downloading dialog, else if response return 500 - show error message in label. I can`t figure it out how to call downloading dialog if pdf returned from ajax
0

Not sure what you're asking for. Just make sure it is a function and call it:

mth1: function (callback) {

   //----need to wrap to something
   setTimeout(function () { 
      console.log("1");
      // be sure it is a function
      if (callback&& getType.toString.call(callback) == '[object Function]';) {
        // call it
        callback();
      }
   }, 1000);

   console.log('2');

}

2 Comments

Still have the same result: 2;3;1
sorry i did not see the part "What I need: 2, 1, 3". You can make the call to the callback inside the function of the setTimeout. Juts make sure, as my answer shows, to check "callback" is executable function so your code does not break if an invalid callback is passed as a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.