Hear the alteration of the JavaScript variable

Suppose there exists a code snippet at point 2

var point2IsReady = true;

At point 1, I am tasked with implementing the following logic:

Once the value of point2IsReady is changed (to true), then display an alert saying 'ready!'.

Considerations:

  • The variable point2IsReady is not accessible in the scope of point 1.
  • The code at point 1 executes before the code at point 2 (or there may be a race condition).

Potential Solution 1

I propose using window.point2IsReady instead and employing setTimeout/setInterval at point 1 until the condition window.point2IsReady === true is met.

Any alternative suggestions? Implementing Listeners or Reacting to Variable Changes?

Note: Only the first occurrence of a change in place2IsReady needs to be tracked.

Can you think of a more optimal approach? Thank you.

Answer №1

To monitor changes in a variable, you can implement a listener using the setTimeout function, as shown below:

let place2IsReady = false;

setReadyListener();

// Simulating a 2-second wait before setting place2IsReady to true
// An alert should be triggered after 2 seconds
setTimeout(() => place2IsReady = true, 2000);

function setReadyListener() {
  const readyListener = () => {
    if (place2IsReady) {
      return alert("Ready!");
    }
    return setTimeout(readyListener, 250);
  };
  readyListener();
}

A more versatile listener 'factory' implementation could be:

let place2IsReady = false;
let fromObj = {
  place2IsReady: "busy",
  done() { this.place2IsReady = "done"; },
};
const listen = changeListenerFactory();

listen(
  () => place2IsReady, 
  () => console.log("place2IsReady") );
listen(
  () => fromObj.place2IsReady === "done", 
  () => console.log("formObj.place2IsReady done!") );
  
console.log("Listening...");

// Testing variable changes with listeners
setTimeout(() => place2IsReady = true, 1000);
setTimeout(() => fromObj.done(), 3000);

function changeListenerFactory() {
  const readyListener = (condition, callback, delay) => {
    if (!condition || typeof condition !== "function") { return true; }
    if (condition()) {
      return callback();
    }
    setTimeout(() => readyListener(condition, callback, delay), delay);
  };
  
  return (condition, callback = () => {}, delay = 250) => 
    readyListener(condition, callback, delay);
}

Alternatively, you may consider utilizing a Proxy with a set trap for monitoring variable changes:

const readyState = new Proxy({ ready: false }, { 
  set (target, prop, val) {
    console.log(`readyState.ready changed from ${target[prop]} to ${val}`);
    target[prop] = val;
  }
});

console.log("Waiting for changes ...");
setTimeout(() => readyState.ready = true, 2000);

Answer №2

If you were to substitute place2IsReady with an object:

place2IsReady = {
  status: false,
  set ready(value) {
      this.status = value
      status && makeCall()
  },
  get ready() { 
    return status
  }
}

makeCall = () => {
  alert('ready')
}

place2IsReady.ready = true

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

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Ways to retrieve form data from a dynamic CDKPortalComponent

I have a dynamic cdkportal component that is created from a variety of Components. These components are added to a modal dialog, and I need to determine the validity of the forms within them. If any of the child component forms are invalid, I want to disab ...

Determine the value added tax in your online shopping basket

Currently, I am in the process of developing a webshop for a pizzeria using Angular, and recently completed work on my cart component. One of the key features I wanted to incorporate was adding a 10% Value-Added Tax (VAT) for each item in the cart and incl ...

Transforming file location to base64 encoded format using TypeScript

I have the path of an image and need to convert it to base64 format, similar to this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg... function encodeImageToBase64(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { va ...

Alignment of the table with a fixed header and scrollable body

Currently, I am experiencing an issue with aligning a table. My aim is to have a fixed header and a scrollable body for the table. To do this, I have aligned the table header and body using: display: table-header-group For the table body, I have applied ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...

Creating Multiple Routes in a Single TypeScript and AngularJS Route File

I have built a module with TypeScript and AngularJS that includes multiple pages. I would like to use one TypeScript controller per page. How can I define multiple controllers in my routes? Currently, I have only defined one, but what if I have 6 or 7 co ...

Error message: "The property or method you are trying to access is not defined

I had no issues with my app until I added the JavaScript, now I'm getting constant errors in the console. One of the errors I see is: Property or method "show" is not defined on the instance but referenced during render. Make sure that this proper ...

Is there a way to display just one element without affecting the other elements within the same class?

I need to create a series of buttons that can appear and disappear when clicked. Here's how it should function: When I click on link 1 (link 2 is currently hidden). Link 2 should then become visible. The challenge lies in distinguishing between mu ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

360 Panoviewer in Three.js exhibits low image quality and pixelated textures

I'm encountering an issue with the texture quality in my 360 panoviewer using Three.js. I've been working off of this code and it appears that my settings are consistent with the original. However, despite using the same image, my version seems ...

When attempting to access AJAX JSON properties using an index within a promise, the result returned is undefined

I have a quiz app that communicates with my server's API using MongoDB. I am trying to access the response indexes in this way: setTimeout(() => { axios.get('/api/ninjas') .then(function (questions) { var data = questions.d ...

Tips for animating a nested array using jQuery

I have a border that is 9x9 with lines, columns, and squares, similar to a Sudoku border. I want to animate it, but I encountered some issues when trying to run multiple animations simultaneously. To solve this problem, I decided to animate one array of el ...

Unable to apply CSS styles to a form input using Ajax

Alright, so I've got this Ajax form that successfully fetches the data and displays it in #register_msg. However, I'm also trying to apply some styles to the input forms. Here's my Ajax code, along with the form. But for some reason, the st ...

Executing multiple JQuery post requests simultaneously

I am currently working with three functions, each of which posts to a specific PHP page to retrieve data. However, since each PHP script requires some processing time, there is a delay in fetching the data. function nb1() { $.post("p1.php", { ...

Notifying the chosen option using jQuery

I have been attempting to display an alert on the webpage based on the selected option. Unfortunately, it appears that my code is not functioning properly. This is what I have tried: $(document).ready(function(){ $("select.country").change(functio ...

Filtering JSON data in AngularJS is simple and effective

I am working with JSON data and I want to display it filtered by genre. The solution provided in the previous question How to filter JSON-Data with AngularJs? did not work for me. Here is myapp.js: var myApp = angular.module('myApp', []); myAp ...

The response header does not contain a valid JWT token

Here's a function I've implemented to authenticate users by creating a response header: function verifyUser(res, id) { const payload = { id } const token = jwt.sign(payload, config.JWT_KEY, { expiresIn: '24h' ...

Implement Angular's ng-show directive within Laravel

I've recently discovered that I can utilize a Laravel variable in an html class and define it in an Angular file. Let me show you the code snippet to better explain: master.blade.php: <div ng-controller="AppCtrl"> <div class =" {{ statusC ...

The content is not displayed in the d3 visualization

While examining the code of this visualization found at http://bl.ocks.org/mbostock/4062045, I noticed that the name from the JSON file is not displaying alongside the nodes. Even though the code includes: node.append("title").text(function(d) { return ...