如何在使用方法链接再次调用之前等待函数运行其路线时重复调用相同的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>