Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animations not being actioned correctly

Can I get fresh eyes on what's happening here, please?

The function is supposed to be: Check for new data, if new > fade out > reload > fade in, if it's not new data don't animate. However now it's fading out and in everytime it checks for new data, which it wasn't doing when I had have it open in dev.

$(function() {
    function reload(elem, interval) {
        var $elem = $(elem);
        var $original = $elem.html();
        $.ajax({
            cache: false,
            url: 'track.php',
            type: 'get',
            success: function(data) {
                if ($original == data) {
                    setTimeout(function() {
                    $("#air_track").fadeOut();
                        reload(elem, interval)
                    $("#air_track").fadeIn("slow");
                    }, interval);
                    return
                }
                $elem.html(data);
                setTimeout(function() {
                    reload(elem, interval)
                }, interval)
            }
        })
    }
    reload('#air_track', 5000)
});

Keep it in mind I've been up for 20+ hours with little sleep so it may actually be really obvious.

like image 289
James Lawson Avatar asked Oct 20 '22 07:10

James Lawson


1 Answers

Try to use the DRY principle - don't repeat yourself.

Set the timeout regardless of data each time, and perform the animation inside the if:

$(function() {
  var reload = function(elem, interval) {
    var $el = $(elem);

    $.ajax({
      cache: false,
      url: 'track.php',
      type: 'get',
      success: function(data) {
        var html = $.parseHTML(data);
        var newText = $(html).text().trim(); 
        var current =  $el.find('span').text().trim(); 
        if (current != newText) {
          $el.fadeOut(function() {
            $el.html(data).fadeIn('slow');
          });
        }
        setTimeout(function() {
          reload(elem, interval);
        }, interval)
      }
    });
  };

  reload('#air_track', 5000);
});
like image 183
Brian Avatar answered Oct 27 '22 16:10

Brian