等待3秒钟,查看变量是否已更改,然后触发一些操作

时间:2018-11-06 22:30:32

标签: javascript variables time debouncing

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

这是场景:

1)用户讲话,然后语音识别将其语音作为文本放入“ speechResult”变量中,并在屏幕上显示。

2)如果用户想说不同的句子,我们将等待3秒钟,以便为用户提供另一个机会。

3)3秒钟后,“ speechResult”没有任何变化,我们触发了一些if语句,以为true或false值分配“ isCorrect”变量...

 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); 

1 个答案:

答案 0 :(得分:1)

您可以像这样使用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一起使用的数字,如果您收到应该取消的条件。或者,您可以使用防抖功能。