Would it be considered improper to implement an endless loop within a Vue.js instance for the purpose of continuously generating predictions with Tensorflow.js?

In my project, I am leveraging different technologies such as Tensorflow.js for training and predicting foods, Web API to access the webcam in my notebook, and Vue.js to create a simple web page.

Within the addExample() method, there is an infinite loop represented by while(true). This loop continuously prompts the model to predict the contents of the webcam frame and updates the result on each iteration.

I am curious to know if having an infinite loop inside a method within my Vue instance could potentially cause any issues.

async addExample() {
  const selector = document.getElementById('classSelector');
  const player = document.getElementById('player');

  // Obtain the intermediate activation from MobileNet 'conv_preds' and feed it to the KNN classifier.
  const activation = this.net.infer(player, 'conv_preds');

  // Add the intermediate activation to the classifier along with the selected class index
  this.classifier.addExample(activation, selector.selectedIndex);

  console.log("Class '" + selector.value + "' has been added to the model");

  while (true) {
    if (this.classifier.getNumClasses() > 0) {
      const activation = this.net.infer(player, 'conv_preds');

      const result = await this.classifier.predictClass(activation);
      this.confidence = result.confidences[result.classIndex];
      this.label = this.foodClasses[result.classIndex].name;
    }
    await tf.nextFrame();
  }
}

This method is executed upon clicking the training button. Despite being triggered only once, it results in entering into an indefinite loop. Subsequent triggering of the same method seems to initiate new loops while the older ones might still be active.

<button type="button" @click="addExample()">Train class</button>

If you wish to view the actual implementation, you can access it via this link.

Update: Thank you for the suggestions provided earlier. I have managed to address my concerns effectively. Now, each time the addExample() function is triggered, it ensures that only one loop is running instead of multiple. This conclusion was drawn by monitoring GPU utilization percentages in the Task Manager.

Prior to this change, each invocation of addExample() would exhibit a gradual increase in GPU utilization percentage.

https://i.stack.imgur.com/gI1dU.jpg

Now, the percentage utilization spikes only once after initiating addExample().

https://i.stack.imgur.com/fiaCZ.jpg

The final revised code snippet is as follows:

async addExample() {
  const selector = document.getElementById('classSelector');
  const player = document.getElementById('player');
  this.infiniteLoopControler += 1;
  const internalLoopControler = this.infiniteLoopControler;

  // Obtain the intermediate activation from MobileNet 'conv_preds' and pass it to the KNN classifier.
  const activation = this.net.infer(player, 'conv_preds');

  // Add the intermediate activation to the classifier along with the selected class index
  this.classifier.addExample(activation, selector.selectedIndex);

  console.log("Class '" + selector.value + "' has been added to the model");

  while (internalLoopControler === this.infiniteLoopControler) {
    if (this.classifier.getNumClasses() > 0) {
      const activation = this.net.infer(player, 'conv_preds');

      const result = await this.classifier.predictClass(activation);
      this.confidence = result.confidences[result.classIndex];
      this.label = this.foodClasses[result.classIndex].name;
    }
    await tf.nextFrame();
  }
}

Thank you for your valuable assistance!

Answer №1

Utilizing await within a (potentially infinite) loop is perfectly acceptable. In fact, using await can be more advantageous than relying on .then, as it eliminates the need for the engine to collect stack traces. To delve deeper into this concept, consider exploring these resources:

  • Uncovering memory leaks in nodejs promise architecture (Insightful thread on Stackoverflow)
  • Understanding asynchronous stack traces: the superiority of await over Promise#then() (Informative blog post by a V8 developer)
  • Constructing a memory-efficient promise chain recursively in javascript (Valuable discussion on Stackoverflow)

If you require a way to halt the loop once it has commenced (such as when clicking a button again), a simple approach would involve modifying your loop to monitor the current iteration.

Sample Code Illustration

let iteration = 0;

async function addExample() {
  iteration += 1;
  const myIteration = iteration;
  while (myIteration === iteration) {
    // ...
  }
}

The provided code snippet offers a basic demonstration. With each invocation of addExample, the iteration variable increments and the ongoing iteration is recorded. Upon subsequent clicks of the button, the initial iteration condition ceases to be satisfied, thereby halting the primary loop.

Answer №2

One approach to eliminating the while(true) is to implement recursion instead.

async addExample() {
  const selector = document.getElementById('classSelector');
  const player = document.getElementById('player');

  // Obtain the intermediate activation of MobileNet 'conv_preds' and provide it
  // to the KNN classifier.
  const activation = this.net.infer(player, 'conv_preds');

  // Pass the intermediate activation to the classifier
  this.classifier.addExample(activation, selector.selectedIndex);

  console.log("Class '" + selector.value + "' added to the model");


  const cb = () => {
    if (this.classifier.getNumClasses() > 0) {
      const activation = this.net.infer(player, 'conv_preds');

      const result = await this.classifier.predictClass(activation);
      this.confidence = result.confidences[result.classIndex];
      this.label = this.foodClasses[result.classIndex].name;
    }
    tf.nextFrame().then(cb);
  }

  cb();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...

Calculating the vertical distance between an element and the top of the page

I am attempting to calculate the distance between the top of an element and the top of the page every time the user scrolls. Although I have managed to make it work, the issue arises when scrolling - the distance remains unchanged. I tried addressing this ...

Could the Redux store be used to access the state related to specific review comments?

I have a react class component that includes state variables. class NewComponent extends Component { state = { modalIsOpen: false, aa: true, bb: false, cc: false, dd: false, ee: 1, dd: [], cc: [], ff: [], gg: [], ...

Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times: this.className != 'selecte ...

Toggle the element within the selected row using Jquery

In order to create a client list, users must click on rows to select them and then submit the selections to the database for a cron job to send out emails. Instead of using checkboxes, I am attempting to highlight rows by including two hidden elements - o ...

What is the correct way to invoke a function within jQuery?

There must be a straightforward solution to what appears to be a simple and regular task. Inside the $(document).ready() function, I aim to invoke a function with a jQuery object - specifically without attaching it to an asynchronous event like mouseover ...

What is the method for triggering the output of a function's value with specified parameters by clicking in an HTML

I am struggling to display a random number output below a button when it is clicked using a function. <!DOCTYPE html> <html> <body> <form> <input type="button" value="Click me" onclick="genRand()"> </form> <scri ...

"Enhancing the Today Button in FullCalendar with Custom Functionality

My issue lies with the implementation of fullCalendar. Specifically, I am utilizing the week view (defaultView: 'basicWeek') with the toolbar buttons for 'today', 'prev', and 'next'. The problem arises when I click t ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

React is generating an error when attempting to use hooks without the appropriate class name prefix

I'm encountering an error when I use hooks without a class name prefix. Can someone help me troubleshoot this issue? import React, {Fragment,useState} from 'react'; function App (props) { const [x,updateX] = useState(1) /* throwing error ...

Separate the string by commas, excluding any commas that are within quotation marks - javascript

While similar questions have been asked in this forum before, my specific requirement differs slightly. Apologies if this causes any confusion. The string I am working with is as follows - myString = " "123","ABC", "ABC,DEF", "GHI" " My goal is to spli ...

Unable to retrieve custom date picker value with React Antd

I have implemented a custom datepicker for entering dates in the 'MMDD' or 'MMDDYY' format. The date value is stored in state and used in the datepicker component as a controlled component. However, upon form submission, the datepicker ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

In Laravel 5.8, I am sending data in JSON format and receiving it using Axios. However, when I try to display the data in a Vue template using v-for,

<template> <div> <div class="row col-md-6 col-md-offset-3 mt-2"> <label> Choose a category: </label> <select name="categories" class="form-control" multiple& ...

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

Tips on customizing Google Analytics code with Google Tag Manager

My website is currently equipped with the Google Analytics tracking code implemented through Google Tag Manager. The standard Google Analytics code typically appears as follows: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']= ...

Create a project using Next.js and integrate it with the tailwindcss framework

My application utilizes TailwindCSS and NextJs. I am facing an issue where certain classes are not working after running npm run start, following a successful run of npm run dev. For example, the classes h-20 / text-white are not functioning as expected, w ...

React and the Use of External Libraries

Currently, I am developing a website with react and I am in need of installing mojs, mojs-timeline, and mojs-curve-editor. Unfortunately, these are not available as npm packages. Can anyone suggest the most effective method to integrate them into my react ...

Moving the words from textArea to each 'ol' element using JavaScript

When a word is entered in the textarea, it should be assigned to a specific class within an 'ol' tag. Each subsequent word will be placed in the next class sequentially. If there are no more words, the remaining classes should remain empty. <! ...

Customizing the appearance of a data field in Angular-ui-grid: Tips and tricks

In my quest through the angular-ui-grid documentation, I have been unable to locate any mention of "CellFormatters" which were utilized in a previous project a few years back. The purpose of the "CellFormatters" was to present a text representation of the ...