In Javascript, a function is executed only once within another function that is set on an interval

Using the Selenium Chrome driver in my JavaScript, I am constantly checking a value on a website every 2 seconds. However, I need to only save status changes to a text file, not every single check. The current code is functional but it saves the text file every two seconds. How can I modify it to store the status changes only? Please assist me with this.

setInterval(MyControl, 2000);

function MyControl() {
  var x = browser.findElements(By.className("textclass")).then(function(divs) {
    var d = new Date();
    if (divs.length == 1) {
      divs.forEach(function(element) {
        element.getAttribute("title").then(function(text) {
          console.log(text, " Control Time :", d.toLocaleString());

          fs.appendFile('mytextfile.txt', text + " Control Time: " + d.toLocaleString() + '\n', function(err) {
            if (err) throw err;
          });
        });
      });
    } else {
      console.log("There isn't any info :" + "Control Time :" + d.toLocaleString());
    }
  });
}

Answer №1

Only write to the file if the current value is different from the previous one.

setInterval(MyControl, 2000);

let previousText = null;

function MyControl() {
  var x = browser.findElements(By.className("textclass")).then(function (divs) {
    // console.log("yy:",divs.length);
    var d = new Date();
    if (divs.length == 1) {
      divs.forEach(function (element) {
        element.getAttribute("title").then(function (text) {
          console.log(text, " Control Time :", d.toLocaleString());
          //    playSound();
          if (text != previousText)
            fs.appendFile('mytextfile.txt', text + " Control Time: " + d.toLocaleString() + '\n', function (err) {
              // console.log("/////////////////////////////////////");
              if (err) throw err;
            });
          previousText = text;
        });
      });
    } else {
      console.log("There isnt any info :" + "Control Time :" + d.toLocaleString());

    }
  });
}

It's worth noting that the following code, rewritten in proper JS style, is much easier to read:

setInterval(MyControl, 2000);

let previousText = null;

function MyControl() {
  browser.findElements(By.className('textclass')).then(divs => {
    if (divs.length !== 1)
      return;
    let date = new Date();
    div[0].getAttribute('title').then(text => {
      if (text !== previousText)
        fs.appendFile('mytextfile.txt', `${text} Control Time: ${date.toLocaleString()}\n`, err => {
          if (err) throw err;
        });
      previousText = text;
    });
  });
}

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

What is the best way to prevent users from entering a zero in the first position of a text box using JavaScript

Although I am aware this may be a duplicate issue, the existing solution does not seem to work for me. The field should accept values like: valid - 123,33.00, 100,897,99, 8000 10334 9800,564,88.36 invalid - 001, 0 ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

Python with Selenium can be used to raise a TimeoutException with a specific message, screen, and stack trace

from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait url = "https://www.electionreturns.pa.gov/General/OfficeRe ...

Is it feasible to conceal a certain field once the user has chosen another field?

Looking to create an IF statement that will help me establish a specific rule. On a customer portal page, customers can open tickets via a form where they provide information such as "software product" and "environment" from dropdown lists, as well as othe ...

retrieve Angular data across components using Input

When using fetch to make a request to the reqres api users in app.component, I then share the data with its child component (hello.component) via Input. While I am able to get the correct user names in the child template, I encounter an issue when trying t ...

Are there alternative methods, aside from using a computed property, that can be utilized to store a Vue route parameter in a way where

In my Vue component, I am working on passing a route parameter through XHR requests and potentially using it in other areas as well. Initially, I considered storing it as a data attribute but realized that it could be modified by someone. Then it occurred ...

Learning the ropes: Building a model with nodejs using tensorflow.js

I am interested in creating an image classifier, but I lack knowledge of python. Since I am familiar with javascript, I have been considering using Tensorflow.js. Can models be trained with Tensorflow.js, and if so, what are the steps involved in the proce ...

Ways to display JSON objects containing nested key-value pairs

In my JSON structure, each Mealplan includes a key and a corresponding value which is an object called meal. id: 1, mealsPerWeek: { Monday: { id: 4, name: "Burger", }, Tuesday: { id: 3, name: "Salad&qu ...

Having Trouble Styling Radio Buttons with CSS

Hello, I'm facing an issue with hiding the radio button and replacing it with an image. I was successful in doing this for one set of radio buttons, but the second set in another row is not working properly. Additionally, when a radio button from the ...

The generation of the page fails due to the absence of defined data

Every time I try to start my server, the error message pops up saying 'data is not defined', even though I have already defined the data content. export default class App extends Component { data = [ { key: "john", val ...

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

Using SCSS to apply a class in Next.js

Currently, I am working on a project using Next.js and implementing the SCSS module procedure for styling. An example component directory structure is as follows: SampleComponent -> index.tsx and SampleComponent.module.scss The code in SampleComponent ...

Where is the best place to insert Javascript code in an HTML file - the head or body section?

I am currently developing a search engine and have implemented code to automatically redirect users from HTTP to HTTPS when they visit my site. The only question I have is whether I should place this code in the head or body section of my webpage. if(wind ...

Discover the sequence that is the smallest in lexicographical order possible

Here is the question at hand Given a sequence of n integers arr, find the smallest possible lexicographic sequence that can be obtained after performing a maximum of k element swaps, where each swap involves two consecutive elements in the sequence. Note: ...

How to modify the content type in an Angular.js $http.delete request

When making a $http.delete request in my Angular app, I include a config object using the following approach: return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]}) This method attaches the values from my d ...

Loop through object in React

I have what seems to be a beginner question with potentially many answers available. The object named Country.js is defined as follows: const Country = { albania: { 'countryNo': 70, 'name': { ...

Ways to update a component when the value of a Promise is altered

I am struggling with Vue component re-rendering due to a problem related to consuming data from a Promise. The data is fetched and stored under the specific property chain (visualData.layout.cube...), where I assign values to DATA properties (such as label ...

Clicking on a table will toggle the checkboxes

I am facing an issue with this function that needs to work only after the page has finished loading. The problem arises due to a missing semicolon on the true line. Another requirement is that when the checkbox toggle-all is clicked as "checked", I want ...

Steps for choosing an option in MUI select list using jest

I am looking for a way to automate tests for a Material UI select component using Jest. Is there a way to select an option from the list of options in the Material UI component and confirm that its value has been successfully populated in Jest? I have se ...

Guide to flattening a nested array within a parent array using lodash

Within my array named sports, there is another array called leagues, but I need to flatten these arrays using _.flatten due to issues with Angular filters. If you look at the data, inside the first array which contains a "name":"Live Betting", there is an ...