user3612986 user3612986 - 7 months ago 16
Javascript Question

How to call the same JavaScript function repeatedly while waiting for the function to run its course before invoking it again, using method chaining?

Using method chaining, I am looking to fire a function repeatedly but only after the function has completed. Almost like don't execute until the function has fully run its course. Example of intended result:

var myfunc = {
copy: function(message){
window.setTimeout(function(){
console.log(message);
},1000);
return this;
}
};
myfunc.copy('hello').copy('world');
// wait a second then log:
// hello
// wait until first function completion (1000ms), wait a second then log:
// world


Any help is appreciated!

Answer

If you don't want to use jQuery you can also have it as a pure JS solution.

var myfunc = {
   timer: null,
   stack: [],
   copy: function(val) {
       if(this.timer == null) {
         console.log(val);
         target.innerHTML += val+"<br />";
         this.timer = setTimeout(function(){myfunc.onComplete();},1000);
       }
       else
         this.stack.push(val);
     
       return this;
   },
   onComplete: function() {
      var val = this.stack.shift();
      console.log(val);
      target.innerHTML += val+"<br />";
      if(this.stack.length) {
        this.timer = setTimeout(function(){myfunc.onComplete();}, 1000);
      }
      else this.timer = null;
   }
};

var target = document.getElementById('target');
var trigger = document.getElementById('trigger');

trigger.onclick = function(){
  myfunc.copy("hello").copy("world");
}
<button id="trigger">Start</button>
<div id="target"></div>

Comments