【问题标题】:How to run a function once in Javascript?如何在Javascript中运行一次函数?
【发布时间】:2020-07-24 00:42:33
【问题描述】:

我正在制作一个程序,如果我的网络摄像头检测到我的手(来自 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()
    }*/
    
});
}

【问题讨论】:

  • 您可以在函数范围之外创建一个布尔值以在条件中使用,并在 if 语句中将其设置为 false
  • 由于某种原因不起作用

标签: javascript function


【解决方案1】:

如果局部变量范围不适用于您的用例,您也可以将其设为 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()
    }*/
    
});
}

【讨论】:

  • 是的,它确实有效,这意味着你的问题是错误的。
  • 或者你对什么时候调用的函数的理解可能是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 2015-12-21
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
相关资源
最近更新 更多