1

I'm working on a video player in ReactJS. Basically, I have set an intro video based on cookies, and it is skippable. When it is skipped, I want my main video to start playing automatically. The way I'm doing it looks like this (the problem lies in the setTimeout() part, I know it makes no sense)

  skipIntro() {
    if (this.state.index === 0) {
        this.handleVisit(MAX_COOKIES_INTRO);
        this.setState({
            index: ++this.state.index,
        });
        this.videoRef.updatePlaybackTime(0);
        setTimeout(() => {
                            this.videoRef.play();
                          }, 0);
    }
}

If I don't use setTimeout, then this.videoRef.play(); does not execute. At first I thought it was because it was being asynchronously called before the main video had time to load. Since I'm waiting 0ms though, I'm very confused. Why does this work? I would really prefer to do this without a setTimeout call.

Big Guy
  • 712
  • 1
  • 8
  • 21
  • 2
    This is probably not the root of your problem, but just a matter of good practice. If you're updating state as a function of the old state, you should use the functional `setState((prevState) => { index: prevState.index + 1 })` pattern. There are more details [in the doc](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) and in [this article](https://medium.com/@shopsifter/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1). – Jules Dupont Jan 30 '18 at 20:50
  • 1
    Thanks. I have a lot of retroactive editing to do... better to know now than before it causes a problem though! – Big Guy Jan 30 '18 at 22:08

1 Answers1

5

setTimeout is a little deceiving in that it will not execute immediately after its time, but instead add the function to the queue after the timeout. In the case of 0ms, instead of immediately executing, it immediately adds it to the current queue.

This doesn't necessarily mean it will execute immediately, but will instead add the function to the queue, where other calls might be waiting to be executed. Without the timeout, it might be executing before whatever other calls need to be made. See this MDN page for more.

In your case, this might mean something required for the main video to play isn't completed when you call without setTimeout, but when using setTimeout, you are still delaying the execution.

You can also look at either of these StackOverflow posts:

What is setTimeout doing when set to 0 milliseconds?

Why is setTimeout(fn, 0) sometimes useful?

tylerwgrass
  • 656
  • 4
  • 19