等待3秒钟,看看变量是否发生了更改,然后启动一些东西



下面是一段使用Web Speech API进行语音识别的JavaScript代码。这段代码负责在用户讲话结束后重新启动语音识别。现在,我想修改此代码,让用户在屏幕上看到speechResult变量时有3秒的机会说出不同的句子。

这是一个场景:

1( 用户说话,然后语音识别将他们的语音作为文本放入"speechResult"变量中,并将其显示在屏幕上。

2( 如果用户想说不同的句子,我们等待3秒钟,再给他/她一次机会。

3( 在"speechResult"没有任何更改的3秒钟后,我们启动一些if语句,为"isCorrect"变量分配true或false值。。。

recognition.onend = function(event) {
//Fired when the speech recognition service has disconnected.
recognition.start();
// Some code to do: If "speechResult" variable changes, wait for 3 
seconds then fire if statement below.//
const debounce = (func, delay) => { 
let debounceTimer 
return function() { 
const context = this
const args = arguments 
clearTimeout(debounceTimer) 
debounceTimer 
= setTimeout(() => func.apply(context, args), delay) 
} 
}  
debounce function() { 

if (speechResult == "who are you") {
isCorrect= true;
} else {
isCorrect= false;
}
} }, 3000); 

您可以这样使用setTimeout

recognition.onend = function(event) {
//Fired when the speech recognition service has disconnected.
recognition.start();
setTimeout(processResult, 3000);
}
function processResult(speechResult) {
if (speechResult == "who are you") {
isCorrect= true;
} else {
isCorrect= false;
}
}

setTimeout返回一个数字,如果您收到一个应该取消它的条件,则可以与clearTimeout一起使用。或者,您可以使用debounce函数。

最新更新