SetInterval not repeating the function execution - javascript

I have a js structure like this:
var intervalID;
function counterUpdater(){
intervalID = setInterval(ajax_counter_upload(),10000);
}
function ajax_counter_upload(){
$.ajax({
type: "POST",
url: "plan/counter.php",
data: {tipo:'BP'},
success: function(data){
$("#spinner_msg").fadeTo(200,0.1,
function(){
$(this).html(data);
$(this).fadeTo(900,1);
});
}
});
}
function ajax_submit(){
var submit_val=$("#stato").serialize();
dest="plan/new_bp1.php";
$.ajax({
type: "POST",
url: dest,
data: submit_val,
success: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_success").html(data1[1]).fadeTo(900,1)});
}else if(data1[0]=="Errore"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_error").html(data1[1]).fadeTo(900,1)});
}
},
complete: function(){
clearInterval(intervalID);
setTimeout(function(){ $('.container').load('plan/home.php');},2000);
}
});
setTimeout(function(){counterUpdater();},2000);
}
Goal would be to run counter_updater each 10 seconds when the ajax_submit starts and to stop it when the ajax_submit ends.
What I get now is to run counter_updater only once.
What am I doing wrong?

There's a mistake in your setInterval call: you have parentheses after the (intended) callback function name, which means that the function is actually called once and setInterval gets only the return value (nothing, in this case).
Simply remove the parentheses:
intervalID = setInterval(ajax_counter_upload, 10000);
// ^^

Related

Firing a function every x seconds

I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds

how to recall function from controller using javascript

setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
var url = '/Lines/dbcheck/?LineID=#ViewBag.LineID&ProductID=#ViewBag.ProductID&LastID=#LastID';
var data = {};
$.get(url, data, function(response_text){
if (response_text == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
}, "text");
}
I already can call function from controller but only 1 time. I would like to create function to check the data from database and return 1 or 0. If it is 0 i would like to make a delay for 5 sec and then recall function again.
the problem is the parameter response_text is not updated because I can call the function from controller only first time
setInterval(makeAjaxCall(),5000);
function makeAjaxCall() {
$.ajax({
cache : false,
dataType: "json",
type: "GET",
async:false,
url: url ,
success: function (fdata) {
if (fdata == 1)
{
document.location.reload();
}
else
{
setInterval(makeAjaxCall(),5000);
}
},
error: function (reponse) {
}
});
}
Your code executed immediately because of you passing () it is not wait for the time delay.
setInterval(makeAjaxCall(), 5000);
change to
setInterval(makeAjaxCall, 5000);
or alternate way
setInterval(function() {
makeAjaxCall();
}, 5000);

simple ajax request with interval

I recently began learning Ajax and jQuery. So yesterday I started to programm a simple ajax request for a formular, that sends a select list value to a php script and reads something out of a database.
It works so far!
But the problem is, that when I click on the send button, it starts the request, 1 second later. I know that it has something to do with my interval. When I click on the send button, I start the request and every second it requests it also, so that I have the opportunity, to auto-refresh new income entries.
But I'd like to have that interval cycle every second, but the first time I press the button it should load immediately, not just 1 second later.
Here is my code:
http://jsbin.com/qitojawuva/1/edit
$(document).ready(function () {
var interval = 0;
$("#form1").submit(function () {
if (interval === 0) {
interval = setInterval(function () {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}, 1000);
}
return false;
});
});
Thanks!
I might be something like the following you're looking for.
$(document).ready(function () {
var isFirstTime = true;
function sendForm() {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}
$("#form1").submit(function () {
if (isFirstTime) {
sendForm();
isFirstTime = false;
} else {
setTimeout(function () {
sendForm();
}, 1000);
}
return false;
});
});
So, use setTimeout when the callback has finished as setInterval just keeps running whether or not your callback has finished.
$(function () {
$("#form1").submit(postData);
function postData() {
var url = "tbladen.php",
data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
setTimeout(postData, 1000);
}
});
return false;
}
});
Kind of related demo

How to prevent duplicated AJAX call?

I'm currently building a simple AJAX call application which will show the result of a textbox after typing some texts inside it:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(document).ready(function(e) {
$("input[name=html]").keyup(function(e) {
if(this.value.length > 1) {
e.preventDefault();
var form = $(this).closest('form');
var form_data = form.serialize();
var form_url = form.attr("action");
var form_method = form.attr("method").toUpperCase();
delay(function(){
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
},1000);
}
});
});
Fiddle Demo
As you can see from the demo above, for instance if you type test,test1 or test2 or any word as long as their length is longer than one then it'll make an AJAX call.
My question is that is there any way that allow me to prevent duplicate AJAX call? For example if I type test in the textbox again, it'll immediately show test in the div without making another AJAX call to fetch the result again. Thank you very much in advance.
You just need to cache previous results and, before making the ajax call, check the cache to see if you already have that result in the cache.
In Javascript, one usually uses an object for a cache:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
// create cache for ajax results
// the key is the form_data
// the value is whatever the ajax call returns
var ajaxCache = {};
$(document).ready(function(e) {
$("input[name=html]").keyup(function(e) {
if(this.value.length > 1) {
e.preventDefault();
var form = $(this).closest('form');
var form_data = form.serialize();
// check the cache for a previously cached result
if (ajaxCache[form_data]) {
// this uses delay, only so that it clears any previous timer
delay(function() {
$("#result").html(ajaxCache[form_data]);
$("#loadingimg").hide();
}, 1);
} else {
var form_url = form.attr("action");
var form_method = form.attr("method").toUpperCase();
delay(function(){
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
// put this result in the cache
ajaxCache[form_data] = returnhtml;
$("#loadingimg").hide();
}
});
},1000);
}
}
});
});
Working demo: http://jsfiddle.net/jfriend00/P2WRk/

When I have a timed poll function, how can I call it manually?

I have the following poll() function:
var pollTimeout = 5000;
(function poll(){
setTimeout(function(){
$.ajax({ url: "/ajax/livedata.php", success: function(data){
if (data[0] == 'success'){
// i'm doing some irrelevant updating here
}
poll();
}, dataType: "json"});
}, pollTimeout);
})();
It's being executed every 5 seconds and everything works fine.
However, how can I execute this function manually? For example, I need to execute it here:
$("#status-update-form textarea").keyup(function(e){
if (e.keyCode == '13'){
var status = $(this).val();
$.get("/ajax/update-status.php", { 'status' : status },
function(data){
$("#status-update-form textarea").val('').blur();
// <-- I need to execute the poll here, so that
// the status is updated immediatelly after it's
// submitted, not when the poll fires seconds later
},'json'
);
}
});
Any idea how can I do this? If I try to fire poll(), it says the function doesn't exist.
Convert your poll to a regular function
var pollTimeout = 5000;
function poll(timeout){
return setTimeout(function(){
$.ajax({ url: "/ajax/livedata.php", success: function(data){
if (data[0] == 'success'){
// i'm doing some irrelevant updating here
}
poll();
}, dataType: "json"});
}, timeout);
}
$("#status-update-form textarea").keyup(function(e){
if (e.keyCode == '13'){
var status = $(this).val();
$.get("/ajax/update-status.php", { 'status' : status },
function(data){
$("#status-update-form textarea").val('').blur();
poll(0);
},'json'
);
}
});
You could split the timeout code from the function it actually calls, then call it manually or automatically.
var pollTimeoutDelay = 5000;
var pollTimeout = null;
function pollNow(){
if (pollTimeout !== null);
clearTimeout(pollTimeout);
pollTimeout = null;
}
// do what you do, then in the callback:
timeout = setTimeout(pollNow, pollTimeoutDelay);
}
You can then call pollNow() whenever you like, it will do the thing, then re set the timeout again.
This method uses three variables in the global scope, if this is a large application it might be worth refactoring it some more.
I wouldn't use setTimeout() in a function in this case. This code below makes sure that the ajax request is killed every time you call poll() (once at start, every 5 seconds and every keyup event call)
var timeout;
var pollTimeout = 5000;
var ajaxCall;
function poll(){
if (null != ajaxCall) {
ajaxCall.abort();
}
ajaxCall = $.ajax({ url: "/ajax/livedata.php", success: function(data){
if (data[0] == 'success'){
// i'm doing some irrelevant updating here
}
poll();
}, dataType: "json"});
}
poll();
timeout = setTimeout(function(){
poll();
}, pollTimeout);
$("#status-update-form textarea").keyup(function(e){
if (e.keyCode == '13'){
var status = $(this).val();
$.get("/ajax/update-status.php", { 'status' : status },
function(data){
$("#status-update-form textarea").val('').blur();
poll();
},'json'
);
}
});

Categories