On line 8 of the code you've posted, you assign a handler function to recognition.onresult:
recognition.onresult = function(event){
// content removed
}
The problem is that, when you hear the word "finished", you don't remove or replace this handler at all. Next time the event is fired, exactly the same handler kicks in again and will print the words.
What you need to do is, when you hear the word "finished", set the onresult handler to something else:
if (Word.indexOf('finished') != -1) {
recognition.onresult = function(event){
// do something different now that we've heard "Finished"
}
test.style.borderColor = "black";
return;
}
Note that from what you describe, what you want is to reassign the initial function (the entire code you assign in line 1) back to the handler again. This is starting to get very convoluted and difficult, since you're now dealing with two anonymous functions, one nested inside the other, and you want to assign the outer one from within the inner one.
In this case, your code will be a lot easier to read if you break these anonymous functions out and give them names so that you can assign/reassign them to recognition.onresult repeatedly.
This is by no means a full implementation and I haven't tested the following, but see if the following makes sense:
recognition.onresult = listenForOkayGoogle;
function listenForOkayGoogle(event) {
var Word = ...;
if (Word.indexOf('okay', 'google') != -1) {
recognition.onresult = listenForNumbersUntilFinished;
}
}
function listenForNumbersUntilFinished(event) {
var Word = ...;
if (Word.indexOf('15') != -1) {
// print it
}
if (Word.indexOf('30') != -1) {
// print it
}
if (Word.indexOf('finished') != -1) {
recognition.onresult = listenForOkayGoogle;
}
}
You start by assigning listenForOkayGoogle as your handler. Whenever the event is fired, this handler kicks in and checks whether one of the magic words has been spoken, and if so it replaces the handler with listenForNumbersUntilFinished. Now, each time the event is fired, that handler kicks in instead. If the word matches one of the relevant numbers, you print it; if instead it matches the word 'finished', you assign the listenForOkayGoogle handler again. You are in effect using the Strategy Pattern here.