How to run a function once in Javascript?

Viewed 55

I'm making a program where if my webcam detects my hand (from Handtrack.js), a text and an image will pop up. Thing is, it executes repeatedly (which makes sense) as long as my hand is present. How do I make it so that it runs only once?

function runDetection(){
model.detect(video).then(predictions => {
    console.log(predictions);
    model.renderPredictions(predictions, canvas, context, video);
    let handSign = predictions[0].bbox;
    let width = handSign[2];
    let height = handSign[3];
    
    if( (width >= 100 && width < 140) && (height >=150 && height < 200)){
        //how to call this once??
        sendApiRequest()
    }
    /*else if ((width >= 300 && width < 400) && (height >=300 && height < 400)){
        sendApiRequest2()
    }*/
    
});
}
1 Answers

If the local variable scope doesn't work there for you use-case you can also make it window.ranOnce as well.

function runDetection(){
model.detect(video).then(predictions => {
    console.log(predictions);
    model.renderPredictions(predictions, canvas, context, video);
    let handSign = predictions[0].bbox;
    let width = handSign[2];
    let height = handSign[3];
    let ranOnce = false;
    
    if(!ranOnce && (width >= 100 && width < 140) && (height >=150 && height < 200)){
        //how to call this once??
        ranOnce = true;
        sendApiRequest()
    }
    /*else if ((width >= 300 && width < 400) && (height >=300 && height < 400)){
        sendApiRequest2()
    }*/
    
});
}
Related