Jump to content

Function problem


Morsusy2k

Recommended Posts

Okay so in my code i have a function that calls itself all the time witch creates a loop:

  $(document).ready(function(){        function runIt() {    //some code here;     runIt();    };    runIt(); }); 

And i want to add another function,but the thing is that code is still in that loop and wont ever load the one i add under it:

$(document).ready(function(){       function runIt() {    //some code here;    runIt();    };    runIt();   //new code    $('#test').click(function(){      $('#slide').slideDown('fast');});

I tried even to put them in separate script tags. Or another .ready function..i cant make them work togetter. Can you give me a hint?Thanks.

Link to comment
Share on other sites

thats a code smell if I ever saw one. what exactly are you trying to do? What does runIt do and why would you want to call it within itself unless you had a really good reason to (which hasn't been mentioned yet). Why do you need to call it so many times onready?

Link to comment
Share on other sites

Two possibilities. 1. Test for a condition that will tell the function to execute or not. A basic pattern is this:

function runIt () {   // some code   if (x == 5) {	  return;   } else {	  runIt();   }}

2. Use a timer, possible with a conditional as I described above.

Edited by Deirdre's Dad
Link to comment
Share on other sites

The function runIt() is just an image slider that will go in loops all the time. That is why i call it inside the function itself. It seemed to me like the simplest way to make something loop forever..

Link to comment
Share on other sites

Try running this code.

function loop(i) {   i++;   loop(i);}loop(0);

You will not be able to interact with the document or execute any other code until an error dialog pops up telling you you're stuck in an infinite loop.

Edited by Deirdre's Dad
Link to comment
Share on other sites

Right, that's the problem. It was just an example. If you put Javascript in an infinite loop then it's going to hang the browser until the loop finishes. For slideshows and animation we use setInterval and setTimeout to run code after a certain amount of time. The browser will wait between executions so that other things can happen.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...