这里是一段使用 Web Speech API 进行语音识别的 JavaScript 代码。这段代码负责在用户说完之后重新启动语音识别。现在我想修改此代码,让用户在屏幕上看到 voiceResult 变量时有 3 秒的机会说出不同的句子。
这是场景:
1) 用户说话,然后语音识别将其语音作为文本放入“speechResult”变量中,并将其显示在屏幕上。
2)我们会等待 3 秒,如果用户想说不同的句子,我们会再给他/她一次机会。
3) 3 秒后“speechResult”没有任何变化,我们触发一些 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
一起使用。或者您可以使用去抖动功能。
关于javascript - 等待 3 秒查看变量是否更改,然后触发某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53181064/