简体   繁体   中英

How to call a function when a variable changes in an API

I am calling an API and updating the objects variables on interval. Within the updateAPI function I wanna check if the variable increases and if it does I wanna call a function.

I have tried setters and getters, storage and other methods. Also played around a lot with different variants of current code but I can't understand the other solutions.

function updateAPI() {
  var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
          callback(null, xhr.response);
      } else {
          callback(status);
      }
    };
    xhr.send();
  };
  getJSON('api.example.com',  function(err, response) {
    if (err != null) {
      console.error(err);
    } else {
      let data = response.data
      var followers = data.followers_count
      var old = followers;

      function check() {
        if (old > followers) {
          console.log('changed');
          var old = followers;
        }
        if (old < followers) { 
          console.log('not changed'); 
          var old = followers; 
        }
      }
      setInterval(check, 5000);

    }
  });
}
updateAPI();
setInterval(() => { updateAPI() }, 10000);

The current code does not log any changes happening to the API. But I can console.log('followers') and see the value changing.

Just some minor things to start:

Move getJSON outside and above of updateAPI . Right now every time it gets called, it is creating a new function which isn't needed. Also you can probably just replace it with the fetch api . You can also abstract the check function and allow it to accept an argument (or two) and tell you if you should update.

Secondly have your tried debugging this some how? Either using console.log statements or the Chrome debugger? The problem lies in this code:

var followers = data.followers_count
var old = followers;

followers and old will always be equal. You're re-assigning them every time you call your function. That is why you're seeing it change, but never seeing it log anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM