Keep setTimeout function running after browser becomes idle - javascript

The following code is used for keeping track of updates from a database.
Problem is it will stop running after some time (probably when the browser becomes idle).
$(function() {
function Update() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
// Call Update again after 30 seconds.
setTimeout(function() { Update(); }, 30000);
}
});
}
// Call postData the first time to start it off.
Update();
});
How can I make it run continually regardless of browser state, or call it back when the window becomes active?

In case of error it will not restart the timer, so there are 2 solution:
A.: add error handler and put the setTimeout(function() { Update(); }, 30000); code into the handler, because in case of error nothing restarts the timer.
disadvantages: callings are not exact 30sec later in case of long time response
$(function() {
function Update() {
var postData = "";
$.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
// Call Update again after 30 seconds.
setTimeout(function() { Update(); }, 30000);
},
error: function() {
setTimeout(function() { Update(); }, 30000);
}
});
}
// Call postData the first time to start it off.
Update();
});
B.: use setInterval instead of setTimer: but you have to schedule only onece, and you have to abort the previous ajax call if the next tick is coming:
$(function() {
var xhr = null;
function Update() {
var postData = "";
if(xhr!=null) { xhr.abort(); } // avoid paralell call of ajax_api.php, so we stop the previous one
xhr = $.ajax({
url: 'functions/ajax_api.php?dashboarddata',
type : 'post',
data: postData,
success: function(resp) {
$('#entradasmas7').html($('#entradasmas7' , resp).html());
$('#entradasmenos7').html($('#entradasmenos7' , resp).html());
}
});
}
// Call postData the first time to start it off.
Update();
setInterval(function() { Update(); }, 30000);
});

Related

Search bar - Add content Dynamicly with Ajax and JQuery

I'm trying to make a search bar which is loading dynamicly content.
However I wish the real content loading start after the user end typing.
I tried this version but it does not work because it does not take into count each event "keyup".
let old_search = ""
let search = ""
$("#search_input").on('keyup paste',function(){
$("#loader_active").show()
$('#videos').empty()
let old_search = $("#recherche").val()
setTimeout(function (){
search = $("#search_input").val()
console.log(old_search + ">" + search)
if (search == old_search){
console.log("loading")
start = 0;
limit = 20;
load(search, start, limit);
start += limit;
}
}, 1000);
});
function load(search, start=0, limit=20) {
$("#loader_active").show()
let form_data = new FormData();
form_data.append('search', search);
form_data.append('start', start);
form_data.append('limit', limit);
$.ajax({
url: "http://website.com/ajax/videos.php",
contentType: false,
dataType: "json",
processData: false,
cache: false,
data: form_data,
type: 'POST',
success: function (data) {
$(data).each(function(index, value) {
showVideo(value) // show video creates divs with jquery containing the data from the json received by the ajax call
})
$("#loader_active").hide()
}
})
}
Does any body know any solution ?
What you can do is to make your function reset a trigger that will fire after x amount of time. Something like:
function myCoolFunction(myParameters) {
//Clear the timeout every time this happens
clearTimeout(window.myTimeout);
//Create a new timeout
window.myTimeout = setTimeout(function() {
//Do Something after 1 second
}, 1000);
}
$(".selector").on('keyup paste', function (){
myCoolFunction(myParameters);
});
This will execute 1 second after the last 'keyup/paste'. :D

Upon success response with data from Ajax call, process additional function as well

I am trying to call function upon successful response from ajax call.
Here both functions:
function waggle() {
var element = $(this);
var tmpClass = element.attr('class');
element.removeClass();
setTimeout(function() {
element.offsetWidth = element.offsetWidth;
element.addClass(tmpClass).addClass('start-now');
}, 10);
}
function auto_load(){
$.ajax({
type: 'POST',
data: {room_id:'$r_room_id',site_id:'$r_site_id'},
url: 'cart_counter.php',
success: function(data){
$('#cart_buble').html(data);
waggle();
}
});
}
This does update #cart_buble div as expected with the number in the cart however doesn't execute waggle function which is responsible for calling css transition effect.
Both functions are working fine seperately.
I think this variable is the problem here.
This kind of function declaration can change the data stored in this variable up to where the function is executed.
Try this way
function waggle() {
var element = $(...); // <--- Query your element instead of using `this`
var tmpClass = element.attr('class');
element.removeClass();
setTimeout(function() {
element.offsetWidth = element.offsetWidth;
element.addClass(tmpClass).addClass('start-now');
}, 10);
}
function auto_load(){
$.ajax({
type: 'POST',
data: {room_id:'$r_room_id',site_id:'$r_site_id'},
url: 'cart_counter.php',
success: function(data){
$('#cart_buble').html(data);
waggle();
}
});
}

Repeated Ajax calls using SetTimeout javascript, unexpected execution

I list of users in a html table that is dynamically created on page load. Each row has an inline button and each button has onclick="functionName(userId)", calls the following functions:On click show the bootstrap model pop up and then after starts calling ajax. The problem is stopping the ajax calls after user has closed model,and if user clicks on another row/user pass the current userId. for some reason, sometimes ajax calls stop and sometimes dont. Previous userId is also being saved somewhere which is resulting double or triple calls in a given interval. Thank you for your insights.
//This function gets called from each row passing its userId:
var timer = null;
function RTLS(id) {
$('#RTLSModal').modal('show');
window.clearTimeout(timer);
$('#RTLSModal').on('hidden.bs.modal',
function() {
window.clearTimeout(timer);
timer = 0;
$('#RTLSModal .modal-body').html("");
$('#RTLSModal').data('bs.modal', null);
});
$('#RTLSModal').on('shown.bs.modal',
function () {
GetRealTimeScans(id);
});
}
function GetRealTimeScans(id) {
var html = '';
$.ajax({
url: '/api/v1/computers/GetRealTimeKeys?computerId=' + id,
typr: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (scans) {
if (scans.length > 0) {
$.each(scans,
function (index, value) {
//create html
});
$('#RTLSModal .modal-body').html(html);
} else {
html += '<div class=""><h3 style="text-align: center;">No one around</h3></div>';
$('#RTLSModal .modal-body').html(html);
}
},
complete: function () {
timer = setTimeout('GetRealTimeScans('+id+')', 10000);
}
});
}
So abort the Ajax call so it stops
var timer = null;
var ajaxCall;
function cleanUp () {
if (timer) window.clearTimeout(timer);
if (ajaxCall) ajaxCall.abort()
}
and when you make the call
cleanUp()
ajaxCall = $.ajax({})
.done( function () {
ajaxCall = null
timer = window.setTimeout(function(){}, 10000)
});
And when you bind the events to the modal, you need to remove the previous event handler.
$('#RTLSModal')
.off('hidden.bs.modal shown.bs.modal')
.on('hidden.bs.modal', function() {})
.on('shown.bs.modal', function() {});

Ajax Uncaught TypeError: in simple function

In my code i am getting this error
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
but when I remove
delay(function(){ ... }, 1000);
from my source file my code works perfectly I don't know what I am doing wrong with it or missing something that is really important to do, here is my full code
function checkurl(textname) {
$.ajax({
type: "POST",
url: "includes/modContent/checkurl.php",
data: "checkurl=" + textname,
dataType:'text', //or HTML, JSON, etc.
success: function(response){
//alert(response);
textname = response;
}
});
return textname;
}
$('input[name=txtPageName]').keyup(function() {
delay(function(){
$('input[name=txtSeoURL]').val(checkurl($(this).val()));
}, 1000);
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
The immediate issue, amongst others, is that you're changing the scope of this when you pass the callback to the setTimeout() handler.
To fix the issue you need to invert your logic so that you set the val() of the field when the AJAX completes instead of using a convoluted method of attempting to return data from an async function. Try this:
var timeout;
$('input[name="txtPageName]"').keyup(function() {
clearTimeout(timeout);
var textname = $(this).val();
setTimeout(function() {
$.ajax({
type: "POST",
url: "includes/modContent/checkurl.php",
data: { checkurl: textname },
dataType: 'text',
success: function(response) {
$('input[name=txtSeoURL]').val(response.trim());
}
});
}, 250);
});

stop the setInterval if the content returned is not empty

So I am retrieving some data via POST using ajax, every 5 seconds, what I am trying to achieve is if the php file ouputs something, then stop the setInterval somehow or set it to 9999999.
Here is what I've tried:
var interval = DEFINEDFROMMYQL;
$(function() {
setInterval(function() {
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
if(html.lenght > 0) {
var interval = 99999999999999;
}
}
});
}, interval);
});
I'm a newbie, so any help will be appreciated.
You can use clearInterval() to stop the timer started by setInterval and correct the typo html.lenght to html.length
// var interval = DEFINEDFROMMYQL;
$(function() {
yourInterval = setInterval(function() {
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
if(html.length > 0) {
///var interval = 99999999999999;
clearInterval(yourInterval);
}
}
});
}, interval);
});
You can handle this a couple of different ways, but based on your question ("stop the setinterval somehow") let's switch the implementation to a setTimeout and also refactor the code in to a function we can recall. So...
var interval = DEFINEDFROMMYQL;
$(function() {
// establish a function we can recall
function getDataFromServer(){
// this encapsulates the original code in a function we can re-call
// in a setTimeout later on (when applicable)
$.ajax({
type: "POST",
url: "url/file.php",
data: "whatever=2",
success: function(html) {
$("#new").html(html);
// only if the length is 0 do we re-queue the function
// otherwise (becase it's setTimeout) it will just die
// off and stop.
if(html.lenght == 0) {
setTimeout(getDataFromServer, interval);
}
}
});
}
// make an initial call to the function to get the ball rolling
setTimeout(getDataFromServer, interval);
// if you want it to execute immediately instead of wait out the interval,
// replace the above line to simply:
//getDataFromServer();
});

Categories

Resources