skip to Main Content

I have written ajax which gets called every second using setInterval() function.

I want to use the ajax response to set text content of a span using innerText.

ajax is getting called every second and is receiving response data from URL.

When data from response remains unchanged for 5 seconds, I want the text content of span tag to be removed.

How can I put condition in ajax call to check if data from response is unchanged for 5 seconds?

setInterval(function() {
      $.ajax({
          type: "POST",

          url: "/data",  // URL to your view that serves new info

      })
      .done(function(data) {
         console.log(data);
      });
}, 1000) 

Any suggestion will be appreciated.
Thank you in advance.

2

Answers


  1. Try something like this:

    var i = 0;
    var prevValue = null;
    
    setInterval(function() {
          $.ajax({
              type: "POST",
    
              url: "/data",  // URL to your view that serves new info
    
          })
          .done(function(data) {
             console.log(data);
             if (prevValue === null) {
                 prevValue = data;       //set initial value on first call
             } else {
                if (data == prevValue) {      //check if data is the same
                    i++;                      //add 1 to counter
                    if(i == 5) {              //if counter reaches 5
                        $('span').text('');   //hide span text
                    }
                } else {                      //if data is not same   
                    i = 0;                    //reset counter
                }
             }
          });
    }, 1000) 
    
    Login or Signup to reply.
  2. Record the time and the data whenever the data changes.

    let dataRecord = {
      time: 0,
      data: null
    };
    
    ...
    
    let dataChanged = (d1, d2) => {
        /* compare d1 & d2, return true if different */
    }
    
    .done(function(data) {
      let nowTime = new Date().getTime();
    
      if (dataChanged(data, dataRecord.data)) {
        dataRecord = {
          time: nowTime,
          data
        };
    
        // update your span content here
    
      } else if (nowTime - dataRecord.time > 5000) {
    
        // remove your span content here
    
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search