延迟到方法链中的下一个功能 [英] Delay to next function in method chain
本文介绍了延迟到方法链中的下一个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更多地了解Javascript中的方法链接,并且想知道在链中的下一个函数中创建没有jQuery的延迟的正确方法:
var foo = function(){
this.delay = function(per){
setTimeout(start,per);
返回此;
};
this.start = function(){
alert('start!');
};
};
var bar = new foo()。delay(1000).start();
解决方案
这不容易做到。 jQuery使用特定队列系统。
<假设你想在没有jQuery的情况下这样做,你必须自己实现一个队列。
例如这个非常简单的实现:
var foo = function(){
var queue = [];
var timer;
this.delay = function(per){
timer = setTimeout(function(){
timer = 0;
var f;
while(f = queue。 shift())f();
},per);
返回此;
};
this.addFunction = function(f){
if(timer)queue.push(f);
else f();
返回此;
};
this.start = function(){
this.addFunction(function(){alert('start')});
返回此;
};
};
如果你想链接另一个未在foo中定义的函数,你可以做
var bar = new foo()。延迟(3000).start()
.addFunction(function(){alert( 另一个连锁的)});
I am trying to learn more about Method chaining in Javascript and would like to know the proper way to create a delay with no jQuery to the next function in the chain:
var foo = function() {
this.delay = function(per) {
setTimeout(start, per);
return this;
};
this.start = function() {
alert('start!');
};
};
var bar = new foo().delay(1000).start();
解决方案
This isn't easy to do. jQuery uses a specific queue system.
Suppose you want to do it without jQuery, you would have to implement a queue yourself.
For example this very simplistic implementation :
var foo = function() {
var queue = [];
var timer;
this.delay = function(per) {
timer = setTimeout(function(){
timer = 0;
var f;
while (f = queue.shift()) f();
}, per);
return this;
};
this.addFunction = function(f) {
if (timer) queue.push(f);
else f();
return this;
};
this.start = function() {
this.addFunction(function(){alert('start')});
return this;
};
};
If you want to chain another function not defined in foo, you may do
var bar = new foo().delay(3000).start()
.addFunction(function(){alert("another chained one")});
这篇关于延迟到方法链中的下一个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文