WISEMAN
WISEMAN

Reputation: 97

Custom solution to implement callback function

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

Upvotes: 0

Views: 103

Answers (2)

Didier Ghys
Didier Ghys

Reputation: 30666

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');

}

Upvotes: 0

mkilmanas
mkilmanas

Reputation: 3485

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

// *snip*
setTimeout(function () { 
    console.log("1");
    callback();
}, 1000);
// *snip*

Upvotes: 2

Related Questions