如何在使用方法链接再次调用之前等待函数运行其路线时重复调用相同的JavaScript函数?
作者:互联网
使用方法链接,我希望重复激活一个函数,但只在函数完成后.几乎就像在函数完全运行之前不执行.预期结果示例:
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解决方案.
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>
标签:method-chaining,javascript 来源: https://codeday.me/bug/20190927/1824752.html