gpt4 book ai didi

Javascript使函数一个接一个地执行

转载 作者:行者123 更新时间:2023-11-30 12:52:39 24 4
gpt4 key购买 nike

我已经设置了一些功能。一个是打字效果,一个是段落效果,另一个是添加“”,另一个是终端中的闪烁光标。所有这些都改变了一个 div 的 innerHTML。

当页面加载函数 Start() 时,它内部有大约 10 个函数,它们构成了一系列应该发生的事情:文本被写入,光标开始闪烁,段落,文本再次写入,等等。

问题是,除非我在 Start() 函数中对每个函数都使用 setTimeout(),否则它们都会同时执行。考虑到我必须为每个功能定义开始时间,这有点困惑。

编辑:这里没有 JQuery。只是javascript。这是我的整个 JS 文件:

ctrl = 0;
y=0;
block = 0;
test = "";
first_time = 1;

function typing(id, sentence){

var index=0;
var intObject= setInterval(function() {
document.getElementById(id).innerHTML+=sentence[index];
index++;
if(index==sentence.length){
clearInterval(intObject);
}
}, 100);
}


function paragraph(x){
while(x>0){
document.getElementById("container").innerHTML+="<br>";
x--;
}
}

function advance(x){
while(x>0){
document.getElementById("container").innerHTML+="&nbsp;";
x--;
}
}


function blink(y){
if(first_time == 1){ctrl = y; first_time=0;}
if(ctrl!=0){
if(block=='0'){
test = document.getElementById("container").innerHTML;
document.getElementById("container").innerHTML+="\u258B";
block=1;
}
else if(block=='1'){
document.getElementById("container").innerHTML=test;
block=0;
}
ctrl--;
setTimeout("blink(y);", 300);
}
if(ctrl==0){first_time=1;}
}


function start(){
typing('container','Subject Name:');
setTimeout("blink('4');",1700);
setTimeout("typing('container',' Carlos Miguel Fernando');",2800);
setTimeout("blink('6');",5600);
setTimeout("paragraph('1');",7200);
setTimeout("blink('8');",7400);
setTimeout("typing('container','Age: 21');",9500);
setTimeout("blink('4');",10800);
setTimeout("paragraph('1');",12800);
setTimeout("blink('4');",13200);
setTimeout("typing('container','Location: Povoa de Varzim, Portugal');",14500);
setTimeout("blink('14');",19000);
setTimeout(function(){document.getElementById("more").style.display="block";}, 23000);
setTimeout("typing('more','Find Out More');",24000);
}

最佳答案

首先,您需要一种方法来确定函数何时结束。理想的机制称为 promise 。 jQuery 中有一个很好的实现。假设在您的事件列表中您想要人为延迟:

blink(4);
sleep(1000); // wait 1 second
blink(4);

像这样实现:

var sleep = function(ms) {
var result = $.Deferred();
setTimeout(result.resolve, ms);
return result.promise();
};

即创建一个 $.Deferred,并返回它的 promise(),但在这两者之间,启动一些将在稍后时间完成的事件。当它发生时,调用 resolve()(这里我只是让 setTimeout 直接调用它)。您可以将一个值传递给 resolve 作为函数的逻辑“返回值”。您也可以改为调用 reject,这在逻辑上类似于抛出异常。

一旦你有了一组返回 promise 的构建 block 函数,你就可以这样做:

typing('container','Subject Name:').then(function() {
return blink('4');
}).then(function() {
return typing('container',' Test');
}).then(function() {
return blink('4');
}).then(function() {
// and so on
});

更新:

Click here to see a quick mock-up in jsbin .

关于Javascript使函数一个接一个地执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20396296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com