簡體   English   中英

如何在 Javascript 中運行一次 function?

[英]How to run a function once in Javascript?

我正在制作一個程序,如果我的網絡攝像頭檢測到我的手(來自 Handtrack.js),就會彈出一個文本和一個圖像。 問題是,只要我的手在場,它就會重復執行(這是有道理的)。 我如何使它只運行一次?

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()
    }*/
    
});
}

如果局部變量 scope 不適用於您的用例,您也可以將其window.ranOnce

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()
    }*/
    
});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM