Limit JavaScript to run X amount of times - javascript

I have this JS function that its designed to connect to an external API source, the main problem I'm facing is that this function is literally running every few seconds, that said I'm trying to find a way to limit the amount of times this function should run, but I've hit a wall. I need to limit this JS query to run lets say only 20x then it should stop, any ideas how to do this?
function updateViewerData(response) {
$('#logged_user_pic').attr('src', response.viewer.photo);
$('#logged_user_name').attr('href', response.viewer.href);
$('#logged_user_name').text(response.viewer.name);
jQuery.ajax({
type: "POST",
url: "https://mysite/api.php?no_redirect=1",
dataType: "json",
data: {
login_id: response.viewer.id,
login_name: response.viewer.name,
login_username: response.viewer.username,
login_level: response.viewer.level,
login_photo: response.viewer.photo,
login_href: response.viewer.href
},
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log("Error! Ajax error");
}
});
}
jQuery(document).ready(function () {
setInterval(updateViewer, 2000);
});

jQuery(document).ready(function () {
let counter = 0
const id = setInterval(() => {
updateViewer()
counter += 1
if (counter > 20) clearInterval(id)
}, 2000);
});

Related

Pausing a timer

I have a page with two tabs that refreshes via timer every thirty seconds. I need to pause/cancel it when either tab-1 is selected or when data is being edited and restart it when tab-0 is selected or when the edit is saved.
The timer variable is in the .html file, the calls to start/stop are in the .js file.
HTML file:
<script>
var interval = setTimeout(function() {
window.location.reload(1);
}, 30000);
</script>
.js file:
The tab timer stop works:
jQuery(document).ready(function() {
jQuery('#tabs').on("click", function() {
var tabIndex = (jQuery("#tabs").tabs('option', 'active'));
if (tabIndex === 0) {
interval = setTimeout(function() {
window.location.reload(1);
}, 30000);
} else {
window.clearInterval(interval);
}
});
});
However, the edit timer stop doesn't work:
jQuery.ajax({
url: 'HandbookServlet',
type: 'POST', data: {formType: "getRecord",
id: id
},
dataType: 'json',
async: false,
success: function(responseText) {
var obj = JSON.stringify(responseText);
var obj2 = JSON.parse(obj);
jQuery('#lblEditDate').text(obj2.strDateSigned);
jQuery('#taEditComment').val(obj2.comment);
jQuery('#divAlert').show();
window.clearInterval(interval); //stop timer doesn't work here
}, error: function(request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
There's no errors generated. Does "window.clearInterval" only work via "jQuery(document).ready"?
The issue wasn't with scope or the timer itself (rather it was "operator headspace and timing").
The problem was that the edit button was on tab0 (which wasn't mentioned in my original question). When that button was clicked, the event propagated to the tab, firing the code in document.ready and restarting the timer after the timer had been stopped in the function.
To fix the problem, I sent the click event to the function and used event.stopPropagation() to prevent the tab from picking up the click:
function displayRecord(e, id) {
e.stopPropagation();
stopTimer();
jQuery.ajax({
url: 'HandbookServlet',
type: 'POST', data: {formType: "getRecord",
id: id
},
dataType: 'json',
async: false,
success: function(responseText) {
var obj = JSON.stringify(responseText);
var obj2 = JSON.parse(obj);
jQuery('#itemId').val(id);
jQuery('#lblEditDate').text(obj2.strDateSigned);
jQuery('#taEditComment').val(obj2.comment);
jQuery('#divAlert').show();
}, error: function(request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
}

How to execute a function to update a json source

I have a Leaflet map that show some weather data from a Json source. I have already a function that update the data every x minutes by a setInterval function.
setTimeout(function () {
refreshId = setInterval(function () {
$.ajax({
method: 'get',
dataType: 'text',
url: 'myURLfile.json',
success: function (data) {
if (data) {
markers = [];
var withoutMarkers = data.slice(10);
markers = JSON.parse(withoutMarkers);
//console.log(markers);
replaceMarkers(currentFactor);
}
},
error: function (err) {
console.error('there is not date for today.', err)
}
})
}, 300000);
},10000)
}
What I would to do now is assign this funtion to a button to execute the refresh fuction manually.
Something like
L.easyButton( 'fas fa-cloud-sun-rain', function(){
myfunction()
}, 'Refresh', {
position: 'topright'
})
But I don't understand what I have to call exactely to do it.
Factor your fetch code out of setInterval and use your newly made function both in setInterval and your button definition.
Something like
function fetchData() {
$.ajax({
method: 'get',
dataType: 'text',
url: 'myURLfile.json',
success: function (data) {
if (data) {
markers = [];
var withoutMarkers = data.slice(10);
markers = JSON.parse(withoutMarkers);
//console.log(markers);
replaceMarkers(currentFactor);
}
},
error: function (err) {
console.error('there is not date for today.', err)
}
});
}
// setup your interval
setInterval(fetchData, 300000);
// setup your button
L.easyButton( 'fas fa-cloud-sun-rain', fetchData, 'Condizioni', {
position: 'topright'
})

Using clearTimeout(x) in ajax call

I am writing codes where the code will do some polling for statistics to the server using AJAX. My web application is getting data from the server every 3 seconds once the server returned the data. It is working good but however, I want to apply clearTimeout(x) function to stop the execution and print something to user when any error occur like "timeout" or "error" triggered by error setting. I managed to search the similar case with me here and this also link. But for some reason my code does not do what I want. Here is what I have so far
var timeoutid = 0;
var myfunc = function() {
$.ajax({
type: "POST",
url: "pull.php",
error: function(xhr, status, error){
if( status==="timeout" || status==="error") {
alert("Timeout or unable to receive statistics!");
clearTimeout(timeoutid);
}
},
success: function(msg){
$('#res').val(msg);
//timeoutid = setTimeout(poll, 3000);
},
complete: function(){
timeoutid = setTimeout(myfunc, 3000);
},
timeout: 5000
});
}
myfunc();
The result of the above when I disable my Internet adapter is it keeps looping and alert me the error without stopping the execution. I don't really know how or where do I put my clearTimeout due to localized variable issue based on what I have read. Not really a master in jQuery in detailed though. Appreciate your kind respond and thank you in advance.
It is because you are again creating a new timer in the complete callback which will get executed in the case of error also
var myfunc = function () {
$.ajax({
type: "POST",
url: "pull.php",
error: function (xhr, status, error) {
if (status === "timeout" || status === "error") {
alert("Timeout or unable to receive statistics!");
}
},
success: function (msg) {
$('#res').val(msg);
},
complete: function (jqXHR, status) {
if (status !== "timeout" && status !== "error") {
setTimeout(myfunc, 3000);
}
},
timeout: 5000
});
}
myfunc();

What's wrong with my ajax function for fetching images?

I’m polling S3 every 5 seconds for an image. My polling is successful and I can see it GETs the URL with the image in web inspector. But the function inside of the done() isn’t executing (I can't see anything logging to console):
(function poll() {
setTimeout(function () {
userId = $('#photo').data('user-id');
photoPath = $('#photo').data('photo-path');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://s3.amazonaws.com/my_bucket/user-photos/'+userId+'/original/'+photoPath,
done: function (data) {
console.log(data);
$("#photo").append(data);
},
complete: poll
});
}, 5000);
})();
What am I doing wrong?
You're asking for dataType: 'json' but you won't get that back because the server is sending an image.
Are you wanting to show the image in $('#photo')?
(function poll() {
setTimeout(function () {
console.log('polling');
userId = $('#photo').data('user-id');
photoPath = $('#photo').data('photo-path');
$('<img>').on('load', function(){
$('#photo').empty().append(this);
poll();
}).prop('src', 'http://s3.amazonaws.com/my_bucket/user-photos/'+userId+'/original/'+photoPath);
}, 5000);
})();
Demo (with image path replaced by jsfiddle logo)

How to use the timer in javascript?

I want to do the following application:
1) I want to retrieve the message using ajax. (Jquery)
2) When I read the message - I want to wait 10 seconds to retrieve the next message
3) Then wait another 10 seconds to retrieve the next message
4) All rows in a database.
How to use the timer in this case?
How can I start and then stop the timer?
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
},"json");
}
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
setTimeout(function(){loadMessage(user_id); }, 10000);
},"json");
}
I prefer calling the next ajax request after the completion of the previous (not as important with 10000 interval), but you do have to call the next one even if the first fails...
function loadMessage(user_id) {
$.ajax({
type: "POST",
url: 'ActionScripts/Message.php',
data: { user_id: user_id }
dataType: 'json',
async: true,
cache: false,
timeout:30000,
success: function(data){
// do what you need with the returned data...
setTimeout(function(){loadMessage(user_id); },10000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//do what you want with the error
setTimeout(function(){loadMessage(user_id); },10000);
}
});
}
The following implementation calls off to the server and executes every 10 seconds:
function loadmessage (user_id) {
$.post('ActionScripts/Message.php', {
user_id: user_id
}, function (data) {
//data
}, "json");
}
var interval = setInterval(function() { loadmessage(5345) }, 10000);
To stop the timer use clearInterval:
clearInterval(interval);
To restart the timer re-initialize the interval variable:
var interval = setInterval(function() { loadmessage(5345) }, 10000);

Categories

Resources