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);
});
Related
i have a script that reload the page when the value is >= 100 the problem is that location.reload(true); are not working in ie11, i also have tried with window.location = self.location.href; but i am having the same problem, in other browsers it works good.
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
}, 2000);
}
});
You don't appear to have defined self anywhere, so you may have an error there. Beyond that, you're trying to assign the value of href as the whole value of location - which is meant to be an object. Instead, try:
window.location.href = window.location.href;
Try to move the if statement into the success callback.
Like that you can clear the interval into the same stack and reload the page on the good
.
$(function() {
if (value < 100) {
var timer = setInterval(function() {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function(msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
},
error: function(err) {
clearInterval(timer);
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
place the if in the success function, ajax is asynchronous the if will execute immediately but value will change after the ajax has completed so the code may never reach the if statement
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value) {
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
location.reload(true);
}
}
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
I would like to compare data to determine if the div needs to be reloaded.
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
var $original = $elem.html();
$.ajax({
cache : false,
url : '/inbox-header.php',
type : 'get',
success : function (data) {
var result = $.trim(data);
var resu = $.trim($original);
console.log(result);
if (result == resu) {
alert('a');
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
$elem.html(data);
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
reload('#inboxheader', 500);
});
// ]]>
When I show the output in the console it looks the same, but the alert never shows, so its always false.
UPDATE:
The output of those variables can be found here, unable to post them here..
http://pastebin.com/abfCk7pH
I dont know why but the trim function did not do his job.
this works:
$(function() {
function reload(elem, interval) {
var $elem = $(elem);
var $original = $elem.html();
$.ajax({
cache: false,
url: '/inbox-header.php',
type: 'get',
success: function(data) {
var opgehaaldedata = data.replace(
/(\r\n|\n|\r)/gm, "");
var orgineledata = $original.replace(
/(\r\n|\n|\r)/gm, "");
if (opgehaaldedata == orgineledata) {
//alert('a');
setTimeout(function() {
reload(elem, interval)
}, interval);
return;
} else {
$elem.html(opgehaaldedata);
setTimeout(function() {
reload(elem, interval)
}, interval);
return;
}
}
});
}
reload('#inboxheader', 500);
});
Why the timeout don't work?
If i work without the function sleep, they return to me an undefined data..
With this function they work but without sleeping time, they go directly to the last image.. :-/
function sleep(value, data, i) {
document.getElementById(value).src = data[i];
}
function imgAnimation(value){
var img = document.getElementById(value).src;
$.ajax({
type: "POST",
url: "static/cercaThumbs.php",
data: 'id=' + value,
datatype: 'json',
success: function (data) {
var elements = Object.keys(data).length;
for (var i = 0; i < elements; i++) {
if(i == elements){i = 0;}
setTimeout(sleep(value, data, i), 300);
}
}
});
}
You need to pass a function to setTimeout. You're calling the function sleep and passing its result.
setTimeout(function() {
sleep(value, data, i);
}, 300);
But it still won't work, because you're setting a bunch of timeouts at the same time, so they'll all trigger 300ms later at the same time. To animate you might try something like:
var data = [
'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0030.png',
'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0031.png',
'https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.2/assets/png/0032.png',
]
var frame = 0;
var elements = data.length;
var animation = setInterval(function() {
frame = (frame + 1) % elements;
document.getElementById('test').src = data[frame];
}, 300);
<img id=test>
This sets up a single repeating callback which can advance to the next frame each time. In the example above it will loop forever, or you can call clearInterval(animation) once you're finished.
Ok, with the help of Nick, this is the correct code:
function imgAnimation(value){
$.ajax({
type: "POST",
url: "static/cercaThumbs.php",
data: 'id=' + value,
datatype: 'json',
success: function (data) {
var elements = Object.keys(data).length;
var frame = 0;
var animation = setInterval(function() {
frame = (frame + 1) % elements;
document.getElementById(value).src = data[frame];
}, 500);
document.getElementById(value).addEventListener("mouseout", function(){
clearInterval(animation);
document.getElementById(value).src = data['0'];
});
}
});
}
I'm sorry the title might not make much sense. I'm not sure how to word what i'm doing.
I have a class that I add to elements that uses HTML5 data attributes to setup a refresh timer. Here is the current code.
$(document).ready(function () {
$('.refresh').each(function() {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var preloader = element.data('show-loading');
var globalPreloader = true;
if (typeof preloader === 'undefined' || preloader === null) {
}
else if (preloader != 'global' && preloader != 'true') {
globalPreloader = false;
}
(function(element, url, interval) {
window.setInterval(function () {
if (!globalPreloader)
{
$('#' + preloader).show();
}
$.ajax({
url: url,
type: "GET",
global: globalPreloader,
success: function (data) {
element.html(data);
if (!globalPreloader) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
})(element, url, interval);
});
$.ajaxSetup({ cache: false });
});
Now I have elements that a user can click on the 'window' which removes it.
These elements can be tired to a timer that was set by the above code.
Code used to remove the element
$(".btn-close").on('click', function () {
var id = $(this).closest("div.window").attr("id");
if (typeof id === 'undefined' || id === null) {
} else {
$('#' + id).remove();
}
});
I need to now kill the timers created for the elements removed.
What is the best way to do this?
Not clear on how you clear them so I do them all here at the end.
$(document).ready(function () {
$('.refresh').each(function () {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var showLoading = element.data('show-loading');
var preloaderID = element.data('preloader-id');
if (typeof showLoading === 'undefined' || showLoading === null) {
showLoading = true;
}
(function (element, url, interval) {
var timerid = window.setInterval(function () {
if (showLoading) {
$('#' + preloaderID).show();
}
$.ajax({
url: url,
type: "GET",
global: showLoading,
success: function (data) {
element.html(data);
if (showLoading) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
element.data("timerid",timerid );//add the timerid
})(element, url, interval);
});
$.ajaxSetup({
cache: false
});
$('.refresh').each(function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
});
Example: remove timer on a click
$('.refresh').on('click', function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
window.setIntervalreturns a handle for the timeout. You can use that to stop the timeout:
var handle = window.setInterval(function() {
window.clearInterval(handle);
}, 1000);
Hope that helps.
Here's a little demo of intervals and "interval assassins". It's a minimal example showing how you can clear intervals in a JavaScript-y way.
$('.start').click(function() {
var $parentRow = $(this).closest('tr')
var $stop = $parentRow.find('.stop')
var $val = $parentRow.children('.val')
// interval
var iid = setInterval(function() {
$val.text(+$val.text() + 1)
}, 10)
console.log(`New Target: ${iid}`)
// interval assassin
$stop.click(function() {
clearInterval(iid)
console.log(`Interval[${iid}] has been assassinated.`)
$(this).off('click')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</tr>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</table>
Just run the snippet to see a demo. Feel free to comment if you have any questions. You can set up multiple intervals by pressing start repeatedly and have them all be cleared at once with a single click of stop.
I need to call a function every 5 minutes for an 8 hour period. The catch is it must be the on the same day. For example if the user logs onto the system at 11:59pm on 3/29 and it's now 12:01am on 3/30 the function should no longer be called.
I know how to call it ever 5 minutes and have the jQuery ajax call coded; that part is fine. My problem is figuring out the date.
Here is the code:
var startDay;
function keepAlive(currDay) {
var today = new Date().getDate();
if (currDay == today) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ alive: 'true' }",
url: "../ses/imsi_ses_edit.aspx/KeepSessionAlive",
dataType: "json",
success: function(data) {
},
error: function(response) {
alert(response.responseText);
}
});
}
}
window.onload = function() {
startDay = new Date().getDate();
keepAlive(startDay); //Make sure the function fires as soon as the page is loaded
setTimeout(keepAlive, 300000); //Then set it to run again after five minutes
}
var initDate = new Date(); // Or get the user login date from an HTML element (i.e. hidden input)
var interval;
function keepAlive() {
// Do stuff (ajax call)
}
window.onload = function() {
keepAlive();
interval = window.setInterval(function() {
var now = new Date();
if(now.getTime() - initDate.getTime() < 8*60*60*1000 && now.getDate() == initDate.getDate()) {
keepAlive();
}
else {
// Stop the interval
window.clearInterval(interval);
}
}, 5*60*1000);
}
function keepAlive(currDay) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ alive: 'true' }",
url: "../ses/imsi_ses_edit.aspx/KeepSessionAlive",
dataType: "json",
success: function(data) {
},
error: function(response) {
alert(response.responseText);
}
});
}
window.onload = function() {
var startDay = new Date().getDate();
var startTime = new Date().getTime();
var interval;
keepAlive(startDay); //Make sure the function fires as soon as the page is loaded
interval = setInterval( function () {
if (startDay != new Date().getDate() || startTime < (new Date().getTime() - 1000*60*60*8)) {
clearInterval(interval);
return;
}
keepAlive();
}, 300000); //Then set it to run again after five minutes
}