javascript: pausing in a loop

7 views
Skip to first unread message

Jonathan Hoyt

unread,
Jul 14, 2009, 9:38:58 PM7/14/09
to south...@googlegroups.com
I'm building a little bit for a page that scrolls thru "features" and
I cannot for the life of me figure out how to do a javascript loop,
and pause during each loop. Anyone done this before and wanna give me
some tips?

Jon Hoyt

Daniel Parker

unread,
Jul 14, 2009, 9:47:35 PM7/14/09
to south...@googlegroups.com
Yup: Build a simple function that, at its end, sets a timeout to run itself again.

var changeItem = function(){}; // it'll probably need this in order to use the function name inside the function itself.

function changeItem() {
  // rotate item in the list, then
  setTimeout(changeItem, 5000); // run again in 5 seconds
}

- daniel parker -

Jonathan Hoyt

unread,
Jul 14, 2009, 9:54:46 PM7/14/09
to south...@googlegroups.com
Is there any way to break out of this?

Jon

Jonathan Hoyt

unread,
Jul 14, 2009, 9:59:10 PM7/14/09
to south...@googlegroups.com
This doesn't seem to work:

  var cycleFacts = function(){};
  function cycleFacts(){
    next_fact();
    setTimeout(cycleFacts, 3000);
  };
cycleFacts();

my function next_fact() works fine from the safari dev console, but using the code above doesn't do anything.

Jon


On Jul 14, 2009, at 9:47 PM, Daniel Parker wrote:

Daniel Parker

unread,
Jul 14, 2009, 10:50:43 PM7/14/09
to south...@googlegroups.com
With a little testing, it looks like you don't need/want the var cycleFacts = function(){}; line.

- daniel parker -

Jonathan Hoyt

unread,
Jul 15, 2009, 12:10:00 AM7/15/09
to south...@googlegroups.com
Ok, this works, but is there any way to "break" the loop?

Jon

Jonathan Hoyt

unread,
Jul 15, 2009, 12:37:36 AM7/15/09
to south...@googlegroups.com
I got it figured out. I ended up doing this:

var stop = 0;

  function cycleFacts(){
    if(stop==0){
      next_fact();
      setTimeout(cycleFacts, 4000);
    };
  };

Then, I can set stop = 1 anywhere else, and it will kill the loop :-)

Jon

On Jul 14, 2009, at 10:50 PM, Daniel Parker wrote:

Daniel Parker

unread,
Jul 15, 2009, 11:04:24 AM7/15/09
to south...@googlegroups.com
You got it. :) I love how Javascript can do that .. just set a variable to stop something else that is going on. To make it more pretty, you could make a function that starts the loop and a function that sets the variable to stop the loop - startLoop(), stopLoop().

- daniel parker -
Reply all
Reply to author
Forward
0 new messages