如何在使用方法链接再次调用之前等待函数运行其路线时重复调用相同的JavaScript函数? [英] How to call the same JavaScript function repeatedly while waiting for the function to run its course before invoking it again, using method chaining?

查看:124
本文介绍了如何在使用方法链接再次调用之前等待函数运行其路线时重复调用相同的JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用方法链接,我希望重复触发一个函数,但只能在函数完成后才能触发。几乎就像在函数完全运行之前不执行。预期结果示例:

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

感谢任何帮助!

推荐答案

如果您不想使用jQuery,您也可以将它作为纯JS解决方案。

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>

这篇关于如何在使用方法链接再次调用之前等待函数运行其路线时重复调用相同的JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆