Calling functions with setTimeout()

后端 未结 6 1442
谎友^
谎友^ 2020-11-21 06:49

Simply put...

why does

setTimeout(\'playNote(\'+currentaudio.id+\', \'+noteTime+\')\', delay);

work perfectly, calling the function

6条回答
  •  伪装坚强ぢ
    2020-11-21 07:31

    I literally created an account on this site to comment on Peter Ajtai's answer (currently highest voted), only to discover that you require 50 rep (whatever that is) to comment, so I'll do it as an answer since it's probably worth pointing out a couple things.

    In his answer, he states the following:

    You can also pass setTimeout a reference, since a reference isn't executed immediately, but then you can't pass arguments:

    setTimeout(playNote, delay);
    

    This isn't true. After giving setTimeout a function reference and delay amount, any additional arguments are parsed as arguments for the referenced function. The below would be better than wrapping a function call in a function.

    setTimeout(playNote, delay, currentaudio.id, noteTime)
    

    Always consult the docs.

    That said, as Peter points out, a recursive function would be a good idea if you want to vary the delay between each playNote(), or consider using setInterval() if you want there to be the same delay between each playNote().

    Also worth noting that if you want to parse the i of your for loop into a setTimeout(), you need to wrap it in a function, as detailed here.

提交回复
热议问题