简体   繁体   中英

Comparing the new value retrieved from an API against the previous value

I'm looking for a solution to compare the new value retrieved from an API call against the previously retrieved value. Using CSS I'll then animate the value to notify the use of a change, currently the value animates each time it is polled no matter if the value is the same or different.

My current solution in jQuery looks like the below. There a plunk of the code here . I've made the code as basic as possible, rather than polling an API it just polls for a random number.

function poll(){
    var data = Math.floor(Math.random() * 3) + 1;
    $("#example").addClass('animate');
    setTimeout(function(){
      $("#example").removeClass('animate');
    }, 2000);

    $("#example").html(data);
  };

  setInterval(poll, 3000);

I think you might want to wrap that code in an anonymous function so that you can hang on to the old value without polluting global scope. So something like this might work:

(function (){

var old = null;

function poll() {
  var data = Math.floor(Math.random() * 3) + 1;

  // compare data with old here
  if( data != old) {
    $("#example").addClass('animate');
    setTimeout(function(){
      $("#example").removeClass('animate');
    }, 2000);
  }

  $("#example").html(data);
  old = data;
};
setInterval(poll, 3000);

})();

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