Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've got a simple function that loops itself. I'd like to kill kill it and then re-execute it based on user action. Not sure what the best way to do it is.

Here's what I've got:

function loopor(){

    $slider.next();

    setTimeout(loopor, 3000);
}

And here's what I need to do:

$('#thing').click(function(event){

    event.preventDefault();

    var thing = $(this);

    /* help here */
    magicKillLooporFunction();
    /* end help*/

    thing.animate({
        height: '100%'
    }, function({
        loopor();
    });
});
share|improve this question

3 Answers

up vote 4 down vote accepted
var myTimeout;
function loopor(){
    clearTimeout(myTimeout);  //Add this so multiple clicks don't create multiple timeouts
    $slider.next();
    myTimeout = setTimeout(loopor, 3000);
}    

And then in the other code

$('#thing').click(function(event){
    event.preventDefault();
    var thing = $(this);
    clearTimeout(mytimeout);
    thing.animate({
    height: '100%'
    }, function({
        loopor();
    });
});
share|improve this answer

Here's the simplest solution:

(function($) {
     var $slider, //Assign value
         timeout;
     function loopor() {
          $slider.next();
          timeout = setTimeout(loopor, 3000);
     }
     $('#thing').click(function(event){

          event.preventDefault();

          var thing = $(this);

          /* help here */
          clearTimeout(timeout);
          /* end help*/

          thing.animate({
              height: '100%'
          }, function({
              loopor();
          });
     });
})(jQuery);
share|improve this answer
This is a better more complete solution than mine, except you'll need to also add a clear timeout in the looper so that the variable timeout doesn't get overwritten if a click happens while animate is in process. – DMoses Nov 19 '12 at 22:07

Add a boolean:

if(keeprunning) setTimeout(loopor, 3000);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.