Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question