Sunday, 4 June 2017

Why does it seem two values are being set to a single variable when using setInterval?

I have this code that listens for a socket emit and then starts an interval loop every 5 seconds. The interval uses jquery to change the text on the page to a value pulled from the socket emit.

   socket.on("activeBid", function(data) {
        $('#noActiveBid').hide();
        $('#activeBid1').hide();
        $('#activeBid').show();
        $('#activeBidValue').text(data.activeBid);
        setInterval(delayTime, 5000);
        function delayTime () {
          $('#ago2').text(moment(data.bidTime).fromNow());
        }
  });

The code gets executed every 5 seconds and everything works well until I emit another socket event, causing a new data value (data.bidTime) to be sent over. The old bidTime value is staying in the interval and the new one is also getting added in so the text on the page changes between the two values every 5 seconds. Why is this?

When I console.log the data.bidTime value and then cause another emit causing another value to be sent over, I get two different values logged to the console every 5 seconds.



via kolbykskk

No comments:

Post a Comment