Javascript how to Constantly check for variable

In Javascript, how do you constantly check for something? For instance, I want something to always display the variable “x”. So how do I display it in an updated fashion? I know in c+ its update(). Can someone help me, please.

It depends. If this is something from the user (for example, a value in an input field) then you would want an event listener on that field. If this comes from a server, you probably need to poll the server to check for data changes. If you’re familiar with the observable pattern from other languages, then you might want to be using rxjs. Frameworks like Angular and React provide data-binding between the model and the view. It really depends on specific problem you’re trying to solve.

In the calculator challenge, I am trying to make the screen display 1234… when the number length reaches 4. I need it to identify when that happens.

Let’s say I have the following html and css representing a screen display for a calculator. For demonstration purposes, I have added a button which will append a random digit (0-9) to the screen display. The code has an if statement which checks if the screen display length is equal to 4. You can insert what ever code you want inside the if statement true block.

HTML

<div id="screen-display"></div>
<button id="btn">Add random digit to display</button>

CSS

body {
  height: 100vh;
  text-align: center;
}

div {
  background: blue;
  color: white;
  font-size: 2em;
  text-align: center;
  width: 50%;
  margin: 10px auto;
  padding: 1em;
}

JavaScript

var screenDisplay = document.getElementById('screen-display');
var btn = document.getElementById('btn');

function randomNum() {
  return Math.floor(Math.random() * 10)
}

btn.addEventListener('click', function(event) {
  screenDisplay.innerText += randomNum();
  if (screenDisplay.innerText.length === 4) {
    // do something
  }
});
2 Likes

You’ll need:
var scrLen=document.getElementById(“screen”).innerHTML.length;

if(scrLen>4){

//doStuff ...

}

Edit: You need to execute this every time when user enters number or operator t execute it …

1 Like