I am having recursive function. it make calls every second. I want to kill that function in certain state.
function foo(){
// ajax call
//in ajax success
success: function(response){
setTimeout(function(){
foo();
},1000);
}
}
This code makes recursive call
if(user == "idile"){
//here i want to kill that foo() function
}
how can i do this ? Thanks in advance
I am having recursive function. it make calls every second. I want to kill that function in certain state.
function foo(){
// ajax call
//in ajax success
success: function(response){
setTimeout(function(){
foo();
},1000);
}
}
This code makes recursive call
if(user == "idile"){
//here i want to kill that foo() function
}
how can i do this ? Thanks in advance
Share Improve this question asked Jun 3, 2011 at 8:35 GowriGowri 16.9k27 gold badges102 silver badges162 bronze badges 1- Did you try to put that condition into the success callback function? – Gumbo Commented Jun 3, 2011 at 8:37
3 Answers
Reset to default 6Assign the timeout to a variable like this:
var timer;
function foo(){
// ajax call
//in ajax success
success: function(response){
timer = setTimeout(function(){
foo();
},1000);
}
}
and then to kill the timer:
if(user == "idile"){
clearTimeout(timer);
}
the way you do is using global variable,
var isFinish= false;
function foo(){
// ajax call
//in ajax success
success: function(response){
setTimeout(function(){
if (!isFinish)
{
foo();
}
},1000);
}
}
and then just change the isFinish to true
if(user == "idile"){
//here i want to kill that foo() function
isFinish = true;
}
When you spawn your function into a different thread, do this:
var t;
function foo()
{
// ajax call
//in ajax success
success: function(response)
{
t = setTimeout
(
function(){foo();}
,1000
);
}
}
When you want to stop it, do this:
if(user == "idile")
{
//here i want to kill that foo() function
clearTimeout(t);
}