1

I want to have a function that can add callback to any function with a delayed timing.

Lets say I have a function :

 function name(val) {
   document.write(val);
 };

Now, adding delayed callback to it ( I don't know what will be the script but I assume it to be called like this ) :

 addCallback( function() {
    name("Arc"); // The Main Function
 }, function() { 
    alert("Done"); // The Callback Function
 }, 1000 // alert will execute only after 1000ms + execution time of the name() function
 );

I found many example in which adding a callback was explained but not delayed callback with timeout + execution time as the delayed time ! Can this be done ?

Thanks In Advance

Debarchito
  • 1,305
  • 7
  • 20

1 Answers1

0

I assume you're looking for something like this?

function name(val) {
  document.write(val);
}

function addCallback(main, callback, ms) {
  return function() {
    main();
    setTimeout(callback, ms);
  };
}

var nameWithCallback = addCallback(function() {
  name("Arc");
}, function() {
  console.log("Done");
}, 1000);

nameWithCallback();

It doesn't add the callback to the existing function (that's impossible), but it returns a new function which calls the existing function and sets a timeout if the existing function doesn't throw an error.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153