Aleksov
Aleksov

Reputation: 1220

Can't stop the looping function

I'm trying to stop the looping function, but it did not work

function ref(){
  var iin=setTimeout(ref,1000);
}

$('#start').click(function(){ ref(); });    
$('#stop').click(function(){clearTimeout(iin);});

Upvotes: 0

Views: 123

Answers (2)

Steve Peak
Steve Peak

Reputation: 2677

You must have the variable outside the function. Called a global variable. And assign it inside your function like so:

var timer;
function go(){
/// STUFF
timer=setTimeout(some_function, 1000);
}

$('#start').click(function(){go();});

$('#stop').click(function(){clearTimeout(timer);});

Upvotes: 3

Salman
Salman

Reputation: 9447

your variable iin is not accessible inside the click event handler. You should make it globally accessible

var iin;
function ref(){
    iin = setTimeout(ref,(scdy/2)-100);
}

$('#start').click(function(){ ref(); });

$('#stop').click(function(){ clearTimeout(iin); });

Upvotes: 5

Related Questions