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

Use vanilla JavaScript to send an AJAX request to a Django view

I'm attempting to make a GET AJAX request to a Django view using vanilla JS. Despite passing is_ajax(), I am having trouble properly retrieving the request object. Below is my JavaScript code. Whether with or without JSON.stringify(data), it does not ...

Utilizing $templateCache with ui-router and minifying in AngularJS 1.x

Posting this as a question-answer post. How can one effectively utilize the $templateCache in the templateProvider of a route within ui-router when attempting to refactor the code? Injection is ineffective, and Angular cannot inject by reference. For ins ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

How can Cucumber be used to validate data from multiple JSON files?

I am currently working with a collection of JSON files within my automation framework. Each JSON file consists of an array containing multiple similar JSON objects. My goal is to utilize these files for validation in a web application using Cucumber and Se ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

Guidelines for integrating Pinia seamlessly into Vue 3 components

How should Pinia's store be correctly used in Vue 3 components? Option A const fooStore = useFooStore(); function bar() { return fooStore.bar } const compProp = computed(() => fooStore.someProp) Option B function bar() { return useFooStore( ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Real-time File Updates Display with Node.js and Express.js

Seeking guidance on whether there is a Node module available to utilize the Express module for displaying real-time updates in the browser using data from a file. I have a regularly updated .csv file and I am looking to showcase these updates instantly on ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...

Printing the object name in CreateJS can be achieved by accessing the name property

var stage = new createjs.Stage("demoCanvas"); console.log(stage.constructor.name);//prints a <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script> <script src="https://code.createjs.com/createjs-2015.11.26.mi ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

Modify the properties of an element based on another

Situation : I am facing a challenge where I need to adjust two components based on a click event. The function linked to the onclick event handleChange includes a prop 'text'. Each time the onclick event is triggered, I must modify the value of t ...

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

Having trouble with Javascript not detecting when it's empty?

Recently, I have been attempting to modify the color of a submit button when a form is empty. As a beginner in this area, I am somewhat puzzled as to what mistake I might be making. I will share the current code with you in hopes of receiving some guidance ...

Struggling to retrieve the Object from a JSON file located at a specific URL

Apologies if this comes across as naive, but my venture into javascript and json is just starting. I'm eager to access the JSON object from the twitter API after executing var myjson; $.getJSON('url of the Object', function(data) { ...

The submit option fails to appear on the screen in the JsonForm library

I've been using the JsonForm library ( https://github.com/jsonform/jsonform ) to define a form in HTML. I have set up the schema and form of the JsonForm structure, but for some reason, the "onSubmit" function that should enable the send button is not ...

Navigating between two intervals in JavaScript requires following a few simple steps

I have created a digital clock with a button that switches the format between AM/PM system and 24-hour system. However, I am facing an issue where both formats are running simultaneously, causing the clocks to change every second. Despite trying various s ...