Javascript中的功能链 [英] Chain of functions in Javascript
问题描述
在javascript中,我们以准并行方式触发函数
In javascript, we fire functions in quasi-parallel
window.onload=function(){
document.getElementById("test").addEventListener('click', function1(), false);
//consider it takes 3 seconds to be completed
document.getElementById("test").addEventListener('click', function2(), false);
}
function1()
完全执行后,如何触发function2()
?
How we can fire function2()
when the function1()
has been completely executed?
在jQuery中,我们可以将一系列函数链接为(例如):
In jQuery, we can chain a series of functions as (for example):
$(this).fadeIn(3000).fadeOut(2000);
如何使用纯JavaScript进行此功能更改?
How to make this change of functions in pure javascript?
编辑:针对负面评论和投票,我提供了以下示例:
In response to a negative comment and vote, I provide this example:
function delay(time, func){
setTimeout(func,time);
}
delay(2000,function(){alert('Function 1');});
delay(1000,function(){alert('Function 2');});
在此示例中,您将首先看到功能2"的警报.
In this example, you'll first see the alert for "Function 2".
推荐答案
我对代码进行了一些修改,以便它使用JSON和更多类似于JQuery的语言...
I amended the code a bit so it uses JSON and more JQuery-like...
function $c(func){
var obj;
if(func=='alert'){
obj={
'queue':[],
'timeout':null,
'alert':function(timeout,prompt){
obj.queue.push({timeout:timeout,prompt:prompt});
if(obj.timeout==null){
obj.timeout=setTimeout(obj.do_alert,timeout);
}
return obj;
},
'do_alert':function(){
var current=obj.queue.shift();
alert(current.prompt);
if(obj.queue.length>0){
obj.timeout=setTimeout(obj.do_alert,obj.queue[0].timeout);
}else{
obj.timeout=null;
}
},
};
}else if(func=='write'){
obj={
'queue':[],
'timeout':null,
'write':function(timeout,text){
obj.queue.push({timeout:timeout,text:text});
if(obj.timeout==null){
obj.timeout=setTimeout(obj.do_write,timeout);
}
return obj;
},
'do_write':function(){
var current=obj.queue.shift();
var node=document.createTextNode(current.text);
document.body.appendChild(node);
if(obj.queue.length>0){
obj.timeout=setTimeout(obj.do_write,obj.queue[0].timeout);
}else{
obj.timeout=null;
}
},
};
}
return obj;
}
$c('alert').alert(1000,"This is an alert...").alert(3000,"...sequence.");
$c('write').write(1500,"Writing with...").write(1000," delay.").write(1000," Yay!");
说明:
这将创建一个返回对象obj
的函数$c
. obj
取决于传递的参数,因此它包含不同的使用方法.分开的呼叫形成不同的队列,因此可以以两种方式(顺序或并行)完成作业.对该函数的调用也会返回obj
,以便可以将函数调用链接在一起.
Explanation:
This creates a function $c
that returns an object obj
. obj
depends on the passed argument so it contains different methods for use. Separated calls forms different queue so jobs can be done in both style, in sequence or parallel. Calls to the function returns obj
also, so that function calls can be chained together.
这篇关于Javascript中的功能链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!