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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With