I am making a Chrome Extension, in which I am using Speech Synthesis. When I type speechSynthesis.getVoices()
in the console I get an Array of 21 different voices. Great!
When I console.log()
the same line within my javascript code, I get an Empty Array in the console. What's the matter, I can't figure out!
As pointed out by @CertainPerformance in the comments, when a page is loaded, it takes some amount of time to populate the voices array as it does so, asynchronously. Due to which when the array is logged into the console immediately after the page loads, we see an empty array...
To fix this, we console log it after some time (say, 10 or 50 ms):
setTimeout(() => {
console.log(window.speechSynthesis.getVoices());
}, <time_in_ms>);
If you want to achieve the same with Promises
, then, here's the code:
function setSpeech() {
return new Promise(
function (resolve, reject) {
let synth = window.speechSynthesis;
let id;
id = setInterval(() => {
if (synth.getVoices().length !== 0) {
resolve(synth.getVoices());
clearInterval(id);
}
}, 10);
}
)
}
let s = setSpeech();
s.then((voices) => console.log(voices)); // Or any other actions you want to take...
Here, after each time interval, we check whether the voices array returned by getVoices()
is empty or not. if it's not, we end up resolving the promise...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With