Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
YouTube API - OnPlayerStateChange event conflict with socket.io

I'm trying to make a web app with youtube iframe api, using socket.io. The goal of the application is to watch and control youtube videos on sync, i was able achieve this with custom controls with the player functions.
But I want to make this happen with the native youtube controls, so I found that it can be done by listening to the events using the onPlayerStateChange() function,

Client:

const onPlayerStateChange = event => {
    console.log(event.data);
    switch (event.data) {
        case 1:
            playVid();
            break;
        case 2:
            pauseVid();
            break;
};

const playVid = () => {
    console.log("play");
    socket.emit(
        "send-data",
        {
            state: "play",
            time: player.getCurrentTime(),
        },
        room
    );
};

const pauseVid = () => {
    console.log("pause");
    socket.emit(
        "send-data",
        {
            state: "pause",
            time: player.getCurrentTime(),
        },
        room
    );
};

socket.on("recv-data", data => {
    if (data.state == "play") {
        if (Math.abs(data.time - player.getCurrentTime()) > 1)
            player.seekTo(data.time);
        player.playVideo();
    } else if (data.state == "pause") {
        player.pauseVideo();
    }
});

Server:

io.on("connection", socket => {
    socket.on("send-data", (data, room) => {
        io.to(room).emit("recv-data", data);
    });
    socket.on("join-room", room => {
        socket.join(room);
    });
});

When more than one player gets connected in a room playing the video, at some point, the player state gets messed up having a series of plays and pauses, so much that the screen freezes.

index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
index.js:107 play
index.js:90 2
index.js:119 pause
index.js:90 1
and goes on...

What Am I doing wrong? and how to correct this?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!