K
K
Krueger2019-04-04 15:04:04
JavaScript
Krueger, 2019-04-04 15:04:04

How to set timer time from json response?

I'm trying to get the time from json in order to use it in setInterval as the time until the next content update. But I can't assign the value obtained from json to the global variable timeRemain. The value works inside the function itself, but I can’t figure out how to make it work outside.
The following work of the script was expected:
We get the time in seconds and some other data from json.
We fasten the received time to SetInterval
After a while, we get new data and a new update time, and so on in a circle.

var timeRemain = 10000; // переменная у которой не удаётся изменить/установить значение
function getData() {
      var dataUpdate = new XMLHttpRequest();
      dataUpdate.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var data = JSON.parse(this.responseText);
          timeRemain = data["remain"] * 1000; // значение для переменной
        }
      };
      dataUpdate.open("GET", "data.json", true);
      dataUpdate.send();
    }

    document.addEventListener("DOMContentLoaded", function() {
      getData();
    });
    setInterval(getData, timeRemain); // время полученное из json

In JSON, the remain field returns seconds indicating how long it will take for new data to be in the json.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2019-04-04
@anon5114

You need

  1. Stop previous timer
  2. Create a new one with a new spacing value

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question