Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an audio element's play method as the callback to setTimeout, why not?

I have a reference to an audio tag whose play method I can call like so:

voice["blessed be"].play()

if I try to call it like:

setTimeout(voice["blessed be"].play, 1000)

I get:

Uncaught TypeError: Illegal invocation

I'm not necessarily going to use setTimeout in the final implementation; but, why doesn't this work?

like image 443
karley Avatar asked May 11 '26 07:05

karley


1 Answers

This is because of how setTimeout calls its callbacks. It calls the callback functions with the context set to window.

So, it's calling voice["blessed be"].play.call(window). This is like calling window.play, which doesn't work. You're taking the play function of an audo element, and forcing it to be ran on the window object. window isn't an audo element, so you get the error.

like image 183
Rocket Hazmat Avatar answered May 13 '26 20:05

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!