user3612986 user3612986 - 2 years ago 95
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){
return this;
// wait a second then log:
// hello
// wait until first function completion (1000ms), wait a second then log:
// world

Any help is appreciated!

Answer Source

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) {
         target.innerHTML += val+"<br />";
         this.timer = setTimeout(function(){myfunc.onComplete();},1000);
       return this;
   onComplete: function() {
      var val = this.stack.shift();
      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(){
<button id="trigger">Start</button>
<div id="target"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download