Suppose I have the following polling function:
function pollingFunc(taskId){
setTimeout(function() {
$.ajax({
url: '/endpoint',
type: 'POST',
data: { 'celery_task_id': taskId },
success: function(response){
if(response.celery_ready) {
console.log('CELERY IS READY')
} else {
console.log('polling')
pollingFunc(response.task_id)
}
}
})
}, 5000);
}
When I invoke it, the success callback is never invoked or it might be, but my console.logs never appear. Instead after a while I get
Uncaught RangeError: Maximum call stack size exceeded
So my function is running recursively, but in the way that I would want it to. I would hope at lease the console log before my recursive calls start would print in the console, but it doesn't. I have confirmed that my backend endpoint is operating correctly and is returning json, so I suspect there is something in my javascript code that I am missing. Anyone have any idea?
1 Answer 1
I'm not good at js, but I had problems with setTimeout. According to w3school:
Display an alert box after 3 seconds (3000 milliseconds):
setTimeout(function(){ alert("Hello"); }, 3000);
So I think your code is waiting 5 secondes before calling your server, and then you call it each time and immediately when you get the answer.
=> To fix your problem, put the setTimeout inside the success function.
function pollingFunc(taskId){
$.ajax({
url: '/endpoint',
type: 'POST',
data: { 'celery_task_id': taskId },
success: function(response){
if(response.celery_ready) {
console.log('CELERY IS READY')
} else {
console.log('polling')
setTimeout(function() {
pollingFunc(response.task_id);
}, 5000);
}
});
}
By the way, to not reproduce that kind of problem, I would also declare separately that function, as advised by JQuery documentation.
4 Comments
pollingFunc, which only queues another setTimeout and exits.
console.logwhatever comes in there? Have you confirmed in the network panel that you're getting a 200 response?setTimeoutis asynchronous and so is$.ajax. NopollingFuncexecution has anotherpollingFuncup the call stack. Something else is going on, that is not shown in your question.