Updated with latest code:
Here is the latest code, still has 2 buttons and 2 functions. Each button should run the relievant function and set the code to run the same button after every minute via the setInterval. For some reason, the very first setInterval always seems to stay set, even after clicking the second button which should change it. Not sure what I'm doing wrong:
$(document).ready(function() {
var myTimer = null;
get_popular();
clearInterval(myTimer);
myTimer = null;
myTimer = setInterval(function() {$('a.btnPopular').click();}, 60*1000);
$('a.btnPopular').click( function(event) {
event.preventDefault();
get_popular( $(this) );
clearInterval(myTimer);
myTimer = null;
myTimer = setInterval(function() {$('a.btnPopular').click();}, 60*1000);
});
function get_popular( that ) {
$.ajax({
url: 'get_popular.aspx?rand=' + Math.random(),
type: 'GET',
error: function(xhr, status, error) {
// error message here
},
success: function(results) {
if ( typeof that != "undefined" ) {
that.closest('.outer_div').find('.inner_div').empty().append( results );
} else {
$('.inner_div.new').empty().append( results ).removeClass('new');
}
}
});
}
$('a.btnLatest').click( function(event) {
event.preventDefault();
get_latest( $(this) );
clearInterval(myTimer);
myTimer = null;
myTimer = setInterval(function() {$('a.btnLatest').click();}, 60*1000);
});
function get_latest( that ) {
$.ajax({
url: 'get_latest.aspx?rand=' + Math.random(),
type: 'GET',
error: function(xhr, status, error) {
// error message here
},
success: function(results) {
if ( typeof that != "undefined" ) {
that.closest('.outer_div').find('.inner_div').empty().append( results );
} else {
$('.inner_div.new').empty().append( results ).removeClass('new');
}
}
});
}
});
Try:
setInterval(function() {$('a.btnPopular').click();}, 60*1000);
Edit:
Also you can't call get_popular(); without a parameter ;)
Edit 2:
This should solve your problems:
var myTimer = null;
$('a.btnPopular').click(function(event) {
event.preventDefault();
get_popular($(this));
clearTimeout(myTimer);
myTimer = setTimeout(function(){$('a.btnPopular').click();}, 60*1000);
});
$('a.btnLatest').click(function(event) {
event.preventDefault();
get_latest($(this));
clearTimeout(myTimer);
myTimer = setTimeout(function(){$('a.btnLatest').click();}, 60*1000);
});
setInterval(function() {$('a.btnPopular').trigger('click');}, 60*1000);
// Ad do this
$(elem).click(function(){}) => $(elem).on('click', function(){});
Related
I'm trying to clear the time interval which runs every 15 seconds.
Here is the ajax request:
function extras()
{
$x = {
action:'extras'
};
var r;
$.ajax({
type:'POST',
url:'services.php',
data:$x,
beforeSend:function() {
$('input[name="stop_"]').trigger("click");
},
success:function(response) {
r = response;
//console.log(response)
},
complete:function() {
console.log(r);
$('input[name="re_start"]').trigger("click");
}
});
}
So, in my buttons re_start and stop_ i have:
$('input[name="re_start"]').click(function (event) {
event.preventDefault();
clearInterval(check);
var check = setInterval(function() {
extras();
},15000);
console.log('Starting again...');
});
$('input[name="stop_"]').click(function (event) {
event.preventDefault();
clearInterval(check);
console.log('Stop');
});
In my DOM in jQuery I initialize the function extras() and keep it in a variable called "check" where I initialize the time interval as follows:
<input type="button" style="display:none;" name="re_start">
<input type="button" style="display:none;" name="stop_">
<script type="text/javascript">
(function() {
extras();
var check = setInterval(function() {
extras();
},15000);
})();
function extras()
{
$x = {
action:'extras'
};
var r;
$.ajax({
type:'POST',
url:'services.php',
data:$x,
beforeSend:function() {
$('input[name="stop_"]').trigger("click");
},
success:function(response) {
r = response;
//console.log(response)
},
complete:function() {
console.log(r);
//message_smart(r);
$('input[name="re_start"]').trigger("click");
}
});
}
</script>
Then I can not understand how it is possible that the first 30 seconds work and when they pass 60 seconds seem to start doing things twice at once, then three and so on! It seems like if I change the interval every second and will run faster and faster. What is the problem?
The problem is here:
(function() {
extras();
var check = setInterval(function() {
extras();
},15000);
})();
You are creating a variable check in a new function scope that is inaccessible outside of that scope. Microsoft has a good example of scope in javascript. Additionally you can see this question.
Now to solve your problem you need to put the check variable in the global scope so remove the function wrapper.
extras();
var check = setInterval(function() {
extras();
},15000);
You also need to change the restart handler to reassign the variable, like so:
$('input[name="re_start"]').click(function (event) {
event.preventDefault();
clearInterval(check);
check = setInterval(function() {
extras();
},15000);
console.log('Starting again...');
});
Now they should all be using the same check variable and work as expected when clearing the timeout.
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);
});
I have an problem with my javascript code
Which gets an value from an ajax script and should update the progress bar.
<script>
function GetProgress(){
$.ajax({url: "percentage.php", success: function(result) {
console.log(result);
var pers = result;
$( "#progressbar" ).progressbar("value",pers.value);
if (pers.value > 0 )
isDone = true;
else
setTimeout(GetProgress(), 2000);
});
};
GetProgress();
</script>
It doesnt work with update it gets the value right but im getting this error:
Uncaught Error: cannot call methods on progressbar prior to initialization; attempted to call method 'value'
Please help :)
Before calling methods of a plugin, you need to initialize it
function GetProgress() {
$.ajax({
url: "percentage.php",
success: function (result) {
console.log(result);
var pers = result;
$("#progressbar").progressbar("value", pers.value);
if (pers.value > 0) {
isDone = true;
} else {
setTimeout(GetProgress, 2000);
}
}
});
};
jQuery(function () {
//initialize the plugin
$("#progressbar").progressbar();
GetProgress();
})
<script>
function GetProgress() {
$.ajax({
url: "percentage.php",
success: function (result) {
console.log(result);
var pers = parseInt(result);
$("#progressbar").progressbar("value", pers);
if (pers.value > 0) {
isDone = true;
} else {
setTimeout(GetProgress, 2000);
}
}
});
};
jQuery(function () {
//initialize the plugin
$("#progressbar").progressbar();
setTimeout(GetProgress, 2000);
})
</script>
Got the solution at last needed to make the value an integer.
Thanks for the solution!
<script type="text/javascript">
var timeOutID = 0;
var checkScores = function() {
$.ajax({
url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/countScoreCh'?>",
success:function(response){
if (response !=' ') {
$('#scoreCh').html(response);
clearTimeout(timeOutID);
} else{
timeOutID = setTimeout(checkScores, 3000);
}
});
}
timeOutID = setTimeout(checkScores,1000);
</script>
I am using setTimeout if there is a change in the database. If there is a change..it will output the change.
My problem is setTimeout will only display the first call.and never checks again if there is another change in the database.
I don't know if setTimeout is the correct way of doing it.
Yeah, setTimeout only runs once though. You're looking for setInterval.
<script type="text/javascript">
var timeOutID = 0;
var checkScores = function() {
$.ajax({
url: "<?php echo 'http://127.0.0.1/ProgVsProg/main/countScoreCh'?>",
success: function(response) {
if(response !== '') {
$('#scoreCh').html(response);
}
}
});
};
timeOutID = setInterval(checkScores, 1000);
</script>
You could also get it working by just getting rid of that else in your success function:
success: function(response) {
if(response !== '') {
$('#scoreCh').html(response);
}
timeOutID = setTimeout(checkScores, 3000);
},
error: function() {
timeOutID = setTimeout(checkScores, 3000);
}
You are making these mistakes
If you want to poll for database changes, don't use setTimeout. Instead use setInterval and clear this interval depending upon your logic like after 50times or something else.
Use a busyFlag because you are making an asynchronous call. (As suggested by #mike)
Try this
var intervalId = null;
var IS_BUSY_FETCHING_UPDATES = false;
var checkScores = function() {
if (!IS_BUSY_FETCHING_UPDTAES) {
IS_BUSY_FETCHING_UPDTAES = true;
$.ajax({
url: "http://127.0.0.1/ProgVsProg/main/countScoreCh"
}).done(function(response){
if (response) {
$('#scoreCh').html(response);
}
}).fail(function(e) {
console.error(e);
}).always(function() {
IS_BUSY_FETCHING_UPDATES = false; // This will be executed when AJAX gets complete
});
}
intervalID = setInterval(checkScores,1000);
I use the function below to check on the status of a JSON file. It runs every 8 seconds (using setTimeout) to check if the file has changed. Once the JSON's status becomes 'success' I no longer want to keep calling the function. Can someone please show me how to do this? I suspect it involves the use of clearTimeout, but I'm unsure how to implement this.
Cheers!
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
}
},
}).always(function () {
setTimeout(checkBookStatus, 8000);
});
};
checkBookStatus();
});
t = setTimeout(checkBookStatus, 8000); when you decide to stop the timeout use this clearTimeout(t);.
use clearTimeout
e.g. you defined :
id = setTimeout(checkBookStatus, 8000);
then you can remove this function by :
clearTimeout(id)
Before your call of checkBookStatus() at the end, put another call: var interval = setInterval(checkBookStatus, 8000);. Then on success you can clearInterval(interval).
Do not use setTimeout for iteration.
A lot of answers are suggesting just to use clearTimeout() however, you are checking the status after the timeout has expired, there is no timeout to clear. You need to not call setTimeout() in your always() function rather than to clear anything. So you could re-inspect the status inside your always() function I suppose, but your data object isn't in scope there. It would be preferable to just use setInterval() outside of your checkBookStatus() function.
$(function() {
var checkBookStatus = function() {
var job_id = "#{#job.job_id}";
var msg = $('.msg');
var msgBuilding = $('#msg-building');
var msgQueuing = $('#msg-in-queue');
var msgSuccessful = $('#msg-successful-build');
var msgError = $('#msg-error');
$.ajax({
url: '/jobs/'+job_id+'/status.json',
datatype: 'JSON',
success:function(data){
if (data.status == "failure") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.queue}") {
msg.hide();
msgQueuing.show();
}
else if (data.status == "#{Job.building}") {
msg.hide();
msgBuilding.show();
}
else if (data.status == "#{Job.failure}") {
msg.hide();
msgError.show();
}
else if (data.status == "#{Job.success}") {
msg.hide();
msgSuccessful.show();
clearInterval(interval);
}
}
});
};
var interval = setInterval(checkBookStatus, 8000);
checkBookStatus();
});
Call clearTimeout with the value previously returned by setTimeout. This would give you something like:
$(function() {
var timeoutID;
var checkBookStatus = function () {
[…]
else if (data.status == "#{Job.success}") {
clearTimeout(timeoutID);
[…]
}).always(function () {
timeoutID = setTimeout(checkBookStatus, 8000);
[…]
When you use setTimeout, use like this:
var myTime = setTimeout(checkBookStatus, 8000);
to clear it just:
clearTimeout(myTime);
the following should work...
the setTimeout function return an instance of the setTimeout function. Keep this value in a variable and pass it to the function clearTimeout when you want to prevent the event from firing again.
i.e.
var t = setTimeout(1000, someFunction);
...
//after you no longer need the timeout to fire, call
clearTimeout(t);