Home > Mobile >  How to prevent function to fire multiple times when triggered
How to prevent function to fire multiple times when triggered

Time:10-31

I am trying to track video progress and send events based on the video current time percentage. However I am having issue when the video is long, for example getPercentage is returning 10 multiple of times on the video because it is rounding up 10.n multiple times. How can I only make the logs to trigger once?



function getPercentage(a, b) {
    return ((a/b)*100)
}
setInterval(() => {
    const progress = Number(getPercentage(currentTime, durationTotal).toFixed(0));
  
  switch(progress) {
    case 10:
        console.log('test 10')
    break;
    case 25:
        console.log('test 25')
    }
}, 1000)

I am expecting that what it is in switch case should trigger only once

CodePudding user response:

You can keep track of the already fired events in an array and check if a value already is in that array. If true, don't log.

var already_sent = [];

if (already_sent.includes(progress) == false){
    already_sent.push(progress);
    console.log(progress);
}

Or if you only want specific percentages to be logged, have an array containing those values and remove when matched:

var log_perc = [10, 25, 50, 75];
if (log_perc.includes(progress) == true){
    log_perc.remove(progress);
    console.log(progress);
}
  • Related