gpt4 book ai didi

javascript - 如何在 Javascript 循环中对事件进行排队

转载 作者:行者123 更新时间:2023-12-01 05:37:43 27 4
gpt4 key购买 nike

我有一个数组,可以在两个人之间创建对话,在浏览器说话和浏览器监听之间“翻转”。

简短版本,如何创建saySomething队列

 for(var i=0; i < speaks.length; i++) {
saySomething(speaks[i]); // saySomething should wait for the previous loop to complete
}

长版

var speak = {}; var speaks = [];
speak.utter = "What do they call a quarter pounder with cheese in Paris?"
speak.speaker = true;
speaks.push(speak);

var speak = {};
speak.utter = "They don't call it a quarter pounder with cheese?"
speak.speaker = false;
speak.time = 3; // listen for 3 seconds
speaks.push(speak);

var speak = {};
speak.utter = "They got the metric system. They call it a Royale with cheese"
speak.speaker = true;
speaks.push(speak);

for(var i=0; i < speaks.length; i++) { //foreach better?
var speak = speaks[i];
if(speak.speaker)
speakThePhrase(speak); // uses SpeechSynthesisUtterance
else
listenAndCompare(speak); // uses webkitSpeechRecognition
// don't attempt to speak while listening is happening and vice-versa
}
doSomethingElse(); don't process this till old the speaking/listening is done

最初我有一个递归循环来移动数组并执行与上面相同的操作,但我认为这种方式可能更容易控制队列。所以要么使用 jQuery deferredJavascript Q我该怎么办?

最佳答案

您没有创建对象队列,您只是隐藏相同的对象并将其再次插入spokes数组,因此您将在数组内多次获得对象的最后版本。

如果您想创建异步行为,您应该尝试回调而不是简单的 for 循环。

最好这样做:

var speak = [
{
utter: "What do they call a quarter pounder with cheese in Paris?",
speaker: true
},
{
utter: "They don't call it a quarter pounder with cheese?",
speaker: false,
time: 3
},
{
utter: "They got the metric system. They call it a Royale with cheese",
speaker: true
}
];

然后你可以使用filtermap等数组方法来处理你需要的数据。

最后,当应用程序中发生某些事情时,您可以使用事件来触发每次讲话。

关于javascript - 如何在 Javascript 循环中对事件进行排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32862268/

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