Javascript how to Constantly check for variable

Javascript how to Constantly check for variable
0.0 0

#1

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.


#2

Can you give us a bit more context to what you are trying to achieve? When you say display variable ‘x’, how would you be displaying it? To the console, to the DOM?


#3

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.


#4

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.


#5

Can you show us the code you have so far (a Codepen perhaps)? It would be much easier to assist you if we could see what you have already tried.


#6

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
  }
});

#7

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 …