1

Javascript:Why setTimeout(audio.play,500) not working?

This is not working(and Firefox 52 said TypeError: 'play' called on an object that does not implement interface HTMLMediaElement.):

setTimeout(document.getElementsByTagName('audio')[0].play,1000.5)

This is working:

setTimeout(function(){document.getElementsByTagName('audio')[0].play()}, 1000.5);

Why?also I can't understand that error prompt

illiterate
  • 289
  • 2
  • 12
  • 1
    No, `.setTimeout` takes a function definition, not a function call. `.play` would be correct, if, you know, it were correct. I like this question. – wassona Apr 18 '18 at 17:39
  • Related: https://stackoverflow.com/questions/5911211/settimeout-inside-javascript-class-using-this – ibrahim mahrir Apr 18 '18 at 17:39
  • `setTimeout(document.getElementsByTagName('audio')[0].play.bind(document.getElementsByTagName('audio')[0]), 1000.5)` would work. – Sebastian Simon Apr 18 '18 at 17:40
  • You can shorten that because you don't need the dom element to find the `play` function, you only need that inside the bind. – René Apr 18 '18 at 17:44

1 Answers1

3

In the first example you pass the function directly as callback to the setTimeout, but that way you will lose the context in which the play function should be called, as of that play is called on the global object, in the case of the browser this will be the window.

That's why you get the error message:

TypeError: 'play' called on an object that does not implement interface HTMLMediaElement.

In the second case you pass a function to setTimeout and this function will then execute:

document.getElementsByTagName('audio')[0].play()

In that case play() is called on the object document.getElementsByTagName('audio')[0] immediately and the return value of that call (which is definitely not a function) is used as setTimeout callback.

Related questions:

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • I'm not sure,is `you will loos the context` meaning `you will lost the context`?I'm basic accept your answer,but `setTimeout(window.play,1000.5)` is not made this same message(even no error massage). – illiterate Apr 18 '18 at 17:55
  • @illiteracy `window.play` is `undefined`, so `setTimeout(window.play,1000.5)` is equal to `setTimeout(undefined,1000.5)` that'y why you don't get an error in that case. `document.getElementsByTagName('audio')[0].play` on the other hand is not `undefined`, but a function. – t.niese Apr 18 '18 at 18:29
  • But `setTimeout(document.getElementsByTagName('audio')[0].play,100)` still same message when I manually made a `window.play` method. – illiterate Apr 19 '18 at 00:16
  • @illiteracy `setTimeout(document.getElementsByTagName('audio')[0].play,100)` does not call the `play` function `window` has, but calles the ` play` function of `document.getElementsByTagName('audio')[0]` in the context of `window`. – t.niese Apr 19 '18 at 05:32