Recurssion in Javascript.

Status
Not open for further replies.

Rhaegar

Ars Tribunus Angusticlavius
7,588
Sorry for all these Javascript and DHTML questions. I'm learning right now and I don't have any really good reference material. I should probably pick up a good book... anyway... I have this function:

Code:
function enlarge(object)
{
  if (object.style.pixelHeight <= ((m11[0])-Base)/Graphinc*Box)      
  {  
    object.style.pixelTop = object.style.pixelTop - 1;
    object.style.pixelHeight = object.style.pixelHeight + 1;
  }
  setTimeout("enlarge1(object)",Speed);
}

Basically this function draws a bar of a certain height when it receives an object. Anyway this does not work unless I change
the object in the setTimeout line to the actual name of the object (ie bar). The code then looks like this:

Code:
function enlarge(object)
{
  if (object.style.pixelHeight <= ((m11[0])-Base)/Graphinc*Box)      
  {  
    object.style.pixelTop = object.style.pixelTop - 1;
    object.style.pixelHeight = object.style.pixelHeight + 1;
  }
  setTimeout("enlarge1(object)",Speed);
}

However, if I do this it means I can't use the function as a generic enlarge function for my other bar objects (i have five) and I need
separate enlarge functions for each one. The problem, I think, is that when the recurssion occurs the object goes out of scope. Can I solve this problem? Thanks
 

Rhaegar

Ars Tribunus Angusticlavius
7,588
sorry I meant the code would look like this

Code:
function enlarge1(object)
{
  if (object.style.pixelHeight <= ((m11[0])-Base)/Graphinc*Box)      
  {  
    object.style.pixelTop = object.style.pixelTop - 1;
    object.style.pixelHeight = object.style.pixelHeight + 1;
  }
  setTimeout("enlarge1(bar1)",Speed);  <---- THIS LINE IS DIFFERENT
}

And I'm calling enlarge1 because i have 5 enlarge functions because the last line doesn't work if I just have
setTimeout("enlarge(object)",Speed). Instead I have to put the name of the object that is being modified...
ie setTimeout("enlarge(bar1)",Speed) and there are 5 objects bar1, bar2 etc
 
Why are you using the setTimeOut() function? If you just write in a function call in the function, then that should be all you need to do. Like this sort of...
Code:
function enlarge(object)
{
   if (object.style.pixelHeight <= ((m11[0])-Base)/Graphinc*Box)      
   {  
      object.style.pixelTop = object.style.pixelTop - 1;
      object.style.pixelHeight = object.style.pixelHeight + 1;
      enlarge(object);              //you need to have your function call in a conditional statement
   }
}
enlarge(bar1);
enlarge(bar2);
It seems like you're going to be calling your setTimeOut() function infintely, with no condition to stop. Am I wrong here? Anyway, this is about all I could do to help.
 

Rhaegar

Ars Tribunus Angusticlavius
7,588
Well the reason I have the setTimeout function is so that I can delay the enlargement of the bar so that it doesn't draw it immediately but rather a slow progression. Anyway it works fun if I put the object name in the setTimeout function. Thanks for trying to help though.

Actually is there something I can use to just pause the javascript for a few seconds that would have the same effect as the setTimeout function. Because if I use your method it works fine but draws the bar immediately rather than slowly.
 

MrMills

Ars Praefectus
3,727
Moderator
Remember, the string passed to setTimeout is executed later and in global scope. So if you give it an argument that only makes sense in local scope, it will get confused.

So you could, for instance, make an Array and put your five objects in it:

Code:
var aObjects = new Array(foo, bar, baz, quux, quuux);
 
function enlarge(iObject)
{
  var object = aObjects[iObject];
 
  if (object.style.pixelHeight <= ((m11[0])-Base)/Graphinc*Box)
  {
    object.style.pixelTop = object.style.pixelTop - 1;
    object.style.pixelHeight = object.style.pixelHeight + 1;
  }
 
  setTimeout("enlarge(" + iObject + ")", Speed);
}
There are other ways to do it, but that's an easy one.
 

Rhaegar

Ars Tribunus Angusticlavius
7,588
Code:
<script>

var Bobjects = new Array(b1,b2,b3,b4,b5);

function enlarge(iobject)
{  
  var object = Bobjects[iobject];
  if (object.style.pixelHeight <= ((m11[0])-Base)/Graphinc*Box)
  {
    object.style.pixelTop = object.style.pixelTop - 1;
    object.style.pixelHeight = object.style.pixelHeight + 1;
  }   
  setTimeout("enlarge(" + iobject + ")", Speed);
}

function make_bars()  // draws the 5 bars
{
     z = "<img id=Bobjects[0] src=\"images/k21d.png\" border=\"0\" style=\"position:absolute; left:357px; top:226px; width:31px; height:0px;\">"
    z = z + "<img id=Bobjects[1] src=\"images/k21d.png\" border=\"0\" style=\"position:absolute; left:423px; top:226px; width:31px; height:0px;\">"
    z = z + "<img id=Bobjects[2] src=\"images/k21d.png\" border=\"0\" style=\"position:absolute; left:489px; top:226px; width:31px; height:0px;\">"
    z = z + "<img id=Bobjects[3] src=\"images/k21d.png\" border=\"0\" style=\"position:absolute; left:555px; top:226px; width:31px; height:0px;\">"
    z = z + "<img id=Bobjects[4] src=\"images/k21d.png\" border=\"0\" style=\"position:absolute; left:621px; top:226px; width:31px; height:0px;\">"
  
  document.write(z);
}

make_bars();
enlarge(0);
enlarge(1);
enlarge(2);
enlarge(3);
enlarge(4);

</script>


This doesn't work. It doesn't do anything now.
Is id=Bobjects[0] correct?
 
I would recommend not using the array approach. It's pretty hack-y, and not very extenisble, especially if you're ever in the mood for dynamically generating objects that can be used without monkeying with a "global array" (one that is always visible to the subroutine). That was actually the first thing I tried, but it turned out to be super un-flexible.

The solution is pretty straight forward: name your variables!

I just wrote a simple little object constructor that added a name to the variables I was declaring, sort of like this:

Code:
function objCreator(obj, varName) {
	this.name = dom?document.getElementById(obj):ie?document.all[obj]:ns?document.layers[obj]:null;	
	if (this.name !== null)	{
		//methods
		this.start    = start;
			
		//variable name required to setInterval()
		this.myName   = varName;
		this.interval = "";
	
		return this;				
	}
	else alert('Your object does not exist');
}

This code takes an object, assigns a name to it, and gives it a hook to disable its timer (if you want to use SetInterval to run even X ms). If you want it to just run once, then you don't even need that part.

So, you can use it after creating some object (like a DIV, or whatever)

Code:
var foo = (someObject, "foo");

So, now you've got a variable with a reference to it's own name, it's own instance (effectively) of the timer function, and it's on interval handle to turn it off with.

The method start might look something like the following (with whatever method you want to invoke):

Code:
function start () {
	this.interval = setInterval(''+this.myName+'.timeline()',10);
}

Anyway, that solves your problem in a general way. It's a problem with scoping, as Mills mentioned, but you can manually add context to your variables and be doing just fine. :)
 

Statik

Ars Scholae Palatinae
1,451
You can pass different variables to a function and make them into object names using :
Code:
//Construct a valid reference to a layer
//in either Netscape or IE
function makeName(layerID) {
    if (navigator.appName=="Netscape") {
        refname = eval("document." + layerID)
    } else {
        refname = eval("document.all." + layerID + ".style")
    }
    return refname;
}

//Slide over xhop,yhop pixels every delay milliseconds
//until the layer reaches xgoal and ygoal
function slide(layerID) {
    var hop=5, delay=25;
    if (layerID) {
        //get this layer's present position
        layerName = makeName("menu" + layerID);
    }

This is only a snippet, so it doesn't close out the second function, but you get the idea.

Statik
 

Rhaegar

Ars Tribunus Angusticlavius
7,588
I think maybe that there are two reasons for this.

1) Some of the threads are so long that people can't read every post so they post their ideas incase it hasn't been mentioned yet. Sometimes this results in duplicate posts.

2) On some boards, especially the programmers board, it might be hard to figure out exactly what one poster is talking about and therefore someone posts something similar because they don't quite understand what someone else means when they post an idea.

Either way I don't really mind seeing duplicate posts. I just browse over things that seems familiar. Whatever the case I appreciate everyone who tried to help me out here. Thanks.
 

Statik

Ars Scholae Palatinae
1,451
I often find that some people create code that does the same thing (same end result) but do it another way (different path). Sometimes, it is so different from the way I think when I program, that I cannot follow the code they posted. Sometimes, different approaches will fit into a greater context better than others.

I have seen many DHTML menu scrollers that proport to be universal, but, although they look really nice, they are designed around text type menu items, rather than graphics. Same end result, but different implimentation.

Statik
 
Status
Not open for further replies.