Update Javascript variable every second

I have a script that retrieves the value "average" from a JSON array

<p id="ticker"></p>


<script>
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function () {
  myObj = JSON.parse(this.responseText);
  document.getElementById("ticker").innerHTML = myObj.average; };
  xmlhttp.open("GET", "https://bitbay.net/API/Public/BTC/ticker.json", true);
  xmlhttp.send();
</script>

I've been trying to figure out how to make the <p> section refresh every few seconds with no success. If anyone could provide some guidance on this, I would greatly appreciate it.

Answer №1

Would you be able to accomplish this task:

<script>
window.setInterval(function(){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function () {
  myObj = JSON.parse(this.responseText);
  document.getElementById("ticker").innerHTML = myObj.average; };
  xmlhttp.open("GET", "https://bitbay.net/API/Public/BTC/ticker.json", true);
  xmlhttp.send();
}, 1000);
</script>

<p>This code snippet triggers the "function" every second (1000 milliseconds). It is recommended to encapsulate it within another function for better structure:</p>

<pre><code><script>
window.setInterval(updateTicker(), 1000);

function updateTicker(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        myObj = JSON.parse(this.responseText);
        document.getElementById("ticker").innerHTML = myObj.average; 
    };
    xmlhttp.open("GET", "https://bitbay.net/API/Public/BTC/ticker.json", true);
    xmlhttp.send();
}
</script>

Answer №2

Using a straightforward setInterval is the solution you are looking for.

<p id="ticker"></p>

<script>  
  var ticker = document.getElementById("ticker");  // Let's store that for quick access

  function updateP(){
     //... Perform your desired actions here
     ticker.innerHTML = "..."
  }

  updateP(); // Initiate an immediate update...
  setInterval(updateP, 3000) // ...followed by updates every 3000ms
</script>

Answer №3

To continuously fetch the JSON data, you can simply use the following code:

setInterval(()=>{//code }, time)
.

setInterval(getAvg, 5*1000); // retrieve data every 5 seconds

function getAvg() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function () {
    myObj = JSON.parse(this.responseText);
    document.getElementById("ticker").innerHTML = myObj.average; 
  };
  xmlhttp.open("GET", "https://bitbay.net/API/Public/BTC/ticker.json", true);
  xmlhttp.send();
}
<p id="ticker"></p>

Answer №4

To accomplish this task, you can utilize the setInterval() function, which allows you to call a function or evaluate an expression at specified time intervals in milliseconds:

function fetchData(){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState==4 && xhr.status==200){
        var data = JSON.parse(this.responseText); 
        document.getElementById("dataDisplay").innerHTML = data.value; 
    }  
  };
  xhr.open("GET", "https://example.com/api/data.json", true);
  xhr.send();
}

setInterval(fetchData, 2000);
<p id="dataDisplay"></p>

NOTE: In order to avoid parse exceptions, it is important to handle the response only if the request was successful.

Answer №5

<p>Press the button and wait for 3 seconds before an alert pops up saying "Hello".</p>
<p id="text">Once you click, the text here will change and a countdown will begin, incrementing every 0.5 seconds. This cycle will continue endlessly...</p>
<button onclick="myFunction()">Give it a go</button>

<script>
var i=0;
function myFunction() {

    setInterval(function(){ document.getElementById('text').innerHTML = i++; }, 500);
}
</script>

</body>
</html>

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

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Themeing for dark mode using styled components in Next JS

I have been searching for an answer to this question, but haven't found one yet Currently, I am using styled components with next js along with the use-dark-mode hook to manage theme changes and detection The global styles switch seems to work fine ...

Exclude the HTML attribute prior to displaying

Is there a way to prevent the src attribute from being used for each img tag until after a certain action is completed? I am trying to modify how images are fetched. Here's what I tried: $('img').each(function() { var elem = $(this); ...

Using pandas to transform nested JSON into a flat table structure

My JSON data structure is as follows: { "a": "a_1", "b": "b_1", "c": [{ "d": "d_1", "e": "e_1", "f": [], "g": "g_1", "h": "h_1" }, { "d": "d_2", "e": "e_2", "f": [], " ...

Avoiding infinite digest loops caused by ng-model with getterSetter in AngularJS

Check out this HTML snippet: <select style="width: 100%;" ng-model="vm.orgType" ng-model-options="{getterSetter: true}" ng-options="orgType as orgType.ORGANIZATION_TYPE for orgType in vm.orgTypes"> </select> Now, let's take a look at the ...

Trouble with jQuery: Tackling a Basic String and Variable Issue

I'm having trouble incorporating my variable into this specific string: var liPad = 20; $(this).css({'width' : width , 'height' : height, 'padding' : "'0px' + liPad + 'px'"}); The desired outcome is ...

Encountering an Issue in Angular 5: Trouble Retrieving Information from Local JSON Source [object Object]

Trying to fetch data from a file named sampledata.json Issues: {{sampledata}} is showing [object Object] {{sampleDataModel.Title}} is throwing an error: TypeError: Cannot read property 'Title' of undefined Contents of sampledata.json: { ...

Is it possible to direct the user to a particular link upon swiping to unlock?

Hello everyone, I could use some assistance with this code. I am looking to redirect someone to a specific page when they swipe to unlock and automatically transfer them to another page when the swipe ends. Any help is greatly appreciated. Thank you! $ ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...

saving a JSON element in a JavaScript array

Currently, I am utilizing AJAX to fetch data from a database using PHP and then converting it into JSON format. <?php echo json_encode($data); ?> This is the AJAX function being used: ajaxCall("getdata.php", container, function (data) { var co ...

Creating a JSON array in JavaScript for future reference

I am interested in creating a JSON array where I can define the fields and add data to it later in my code. However, I am unsure about the correct syntax to achieve this. So far, my attempts have resulted in some parse errors; <script> var myJSONAr ...

What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with: bodyLength.forEach((el, i) => { console.log(`${values.bodyTitleEn2 + i.toString()}`); body.push({ title: [ { key: 'en', value: values.bodyTi ...

Having trouble finding a solution because Ajax/JSON is only retrieving a single result from the PHP/SQL file

I am facing an issue with retrieving data through AJAX/JSON from another file containing a PHP While loop. The problem is that only one data is being returned instead of the expected 11 rows. Despite researching extensively on Google, YouTube, and other so ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...

At what point is it appropriate for me to delete the token?

Seeking Answers: Token Dilemmas Is it best to create the token upon user login and registration, or just on login? Should the token be saved in local storage? Do I need to send the token after every user request? Should the token o ...

Verifying the presence of an object in an array based on its value using TypeScript

Having the following dataset: roles = [ {roleId: "69801", role: "ADMIN"} {roleId: "69806", role: "SUPER_ADMIN"} {roleId: "69805", role: "RB"} {roleId: "69804", role: "PILOTE"} {roleId: "69808", role: "VENDEUR"} {roleId: "69807", role: "SUPER_RB"} ] The o ...

How to manage simultaneous requests in Parse Server Cloud Code

Imagine having some Cloud Code running on a Parse Server: Parse.Cloud.beforeSave("UserProfiles", function(request, response) { const query = new Parse.Query("UserProfiles"); query.equalTo("user", request.user); query.count({ success: f ...

What is the best approach to extract data from this specific JSON array within Android Studio?

[{"error":"no error"}] [{"uid":"20","uname":"Velani Hasnain Raza","uage":"13","umo":"98658912","city":"jhguva","state":"Gffhat", "country":"Ingja","pass":"000000gg0","image":""}] [{"rank":"NA","total":"6","score":"3","played":"2"}] .......displaying user ...

Forward the jsp to the servlet before navigating to the following page

Issue: After submitting the JSP form on Page1, it redirects to a server-side JSP page but appears as a blank page in the browser. Instead, I want it to redirect to Page2 which includes a list box that highlights the newly created item. Seeking help with t ...