竞争条件:尝试在加载 React 之前播放视频 [英] Race condition: Trying to play a video before it loads React

查看:33
本文介绍了竞争条件:尝试在加载 React 之前播放视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ReactJS 开发视频播放器.基本上,我已经设置了一个基于 cookie 的介绍视频,它是可跳过的.当它被跳过时,我希望我的主视频自动开始播放.我的做法是这样的(问题出在 setTimeout() 部分,我知道这没有意义)

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

如果我不使用 setTimeout,则 this.videoRef.play(); 不会执行.起初我以为是因为它在主视频有时间加载之前被异步调用.由于我正在等待 0ms,所以我很困惑.为什么这样做?我真的更愿意在没有 setTimeout 调用的情况下执行此操作.

解决方案

setTimeout 有点欺骗性,它不会在超时后立即执行,而是将函数添加到队列中暂停.0ms的情况下,不是立即执行,而是立即加入当前队列.

这并不一定意味着它会立即执行,而是将函数添加到队列中,其他调用可能正在等待执行.如果没有超时,它可能会在需要进行任何其他调用之前执行.有关更多信息,请参阅此 MDN 页面.

在您的情况下,这可能意味着当您在没有 setTimeout 的情况下调用时,主视频播放所需的某些内容未完成,但是当使用 setTimeout 时,您仍然延迟执行.

您还可以查看以下任一 StackOverflow 帖子:

setTimeout 设置为 0 毫秒时在做什么?

为什么 setTimeout(fn, 0) 有时有用?>

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.

解决方案

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?

这篇关于竞争条件:尝试在加载 React 之前播放视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆