Daniel Shen
Daniel Shen

Reputation: 99

More elegant way to handle progress update notifications

Hi i'm currently tracking the uploading of a file (as it compresses) and sending the progress back to the user through the GUI. My code is somewhat ugly-looking. Wondering if you guys might have a better way?

The booleans below are meant to prevent constant updates as i only want to update at certain 'checkpoints'. (in this case below, 25%, 50% and 75%).

let past25 = false;
let past50 = false;
let past75 = false;

ffmpeg(file.path)
.addOption('-hls_time', 10)
.addOption('-hls_list_size', 0)
.addOption('-f', 'hls')
.on('progress', (progress) => {
    let sendUpdate = false;

    if (progress.percent > 25 && past25 == false) {
        sendUpdate = past25 = true;
    } else if (progress.percent > 50 && past50 == false) {
        sendUpdate = past25 = past50 = true;
    } else if (progress.percent > 75 && past75 == false) {
        sendUpdate = past25 = past50 = past75 = true;
    }

    if (sendUpdate) {
        notifyUser(progress)
    }
})

Upvotes: 0

Views: 50

Answers (1)

pilchard
pilchard

Reputation: 12919

Perhaps set an initial threshold and an increment and then use a single check. Also allows you to change the granularity of your updates by just changing the values.

let threshold = 25;
let increment = 25;

ffmpeg(file.path)
  .addOption('-hls_time', 10)
  .addOption('-hls_list_size', 0)
  .addOption('-f', 'hls')
  .on('progress', (progress) => {

    if (progress.percent > threshold) {
      notifyUser(progress);
      // account for skipping multiple 'checkpoints' by rounding to the next highest threshold
      threshold += Math.ceil((progress.percent - threshold) / increment) * increment;
    }

  });

Upvotes: 1

Related Questions