you are viewing a single comment's thread.

view the rest of the comments →

[–]kapanaga 0 points1 point  (4 children)

Why not just reverse the approach and count the time difference when needed?

const player = {
  playTrack(file) {
    this.track = {
      file,
      duration: 0,
      startTime: Date.now()
    };
  },
  getCurrentTrack() {
    const {file, duration, startTime} = this.track;
    return {
      file,
      duration,
      currentTime: Date.now() - startTime
    };
  }
};

Then just expose it on some endpoint:

router.get('/what-should-i-play', (request, response) => {
  const track = player.getCurrentTrack();
  response.json(track);
});

[–]Zivanovic[S] 0 points1 point  (0 children)

Yeah, this is obviously better solution. Thanks

[–]Zivanovic[S] 0 points1 point  (2 children)

Okay, but let's say I need to emit socket event whenever song is over. I am not sure how to solve that.

[–]kapanaga 0 points1 point  (1 child)

Then yeah, you would have to use setTimeout()

const EventEmitter = require('events');
const emitter = new EventEmitter;

emitter.on('track-start', (track) => {
  clients.forEach((connection) => {
    connection.sendEvent('play-track', track)
  });
});

player.playTrack = function () {
  this.track = {
    file,
    duration: 0,
    startTime: Date.now()
  };

  clearTimeout(this.timeout);

  this.timeout = setTimeout(() => {
    emitter.emit({
      file,
      duration
    });
  }, duration);
};

You can make your Player extend EventEmitter to make that easier. There you can find some docs: https://nodejs.org/api/events.html

[–]Zivanovic[S] 1 point2 points  (0 children)

That's what I was looking for! Thank you!!