473,405 Members | 2,373 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

setTimeout() recursion problem

5
Hello,

I'm currently studying javascript by myself.
I thought that I will write js that will remove element in the body from DOM every 2 seconds, untill all elements in the body are deleted( except debug <span> :) )

At first I tried to go through the elements with loop, but when I call setTimeout() the loop doesn't wait setTimeout() to end, but it continues looping.

Now I use recursion. setTimeout() call the function which do the stuff.

But when there is more nested tag( as in the sample html below <ul><li></li</ul> ) inner recursive function( cDestoyer() at the middle of the function body ) stops for some reason.
And whole ul is deleted, not element by element.

When I don't use setTimeout(), recursion is working correctly.

Any help will be appreciated.

Here is the example: http://www.svubit.eu/iskren/
Aug 18 '07 #1
4 5195
jx2
228 100+
i am surprice it works at all!!
your.js file is one line and there are coments in it !! so its meen part of the code is commented... isnt it?

could you post your code?

regards jx2
Aug 18 '07 #2
si4
5
May be there is problem with line breaks, because file is created with gnu/linux editor and some windows editors show it as one line.

This is the code in the js file:

Expand|Select|Wrap|Line Numbers
  1. function cDestroyer( node, it ){
  2.     if( !node){ var node = document.body }
  3.  
  4.     var stuffToDestroy = node.childNodes;
  5.  
  6.     if( it ){ it = parseInt(it);}
  7.     if( !it ) { it= stuffToDestroy.length - 1;}// we start from the end of the dom tree
  8.     var target = stuffToDestroy[it];
  9.  
  10.     if( target ){// no " ... has no properties" error
  11.         if( target.nodeType == 1)//we need to delete only elements
  12.         {
  13.             debug("--node=" +node.nodeName + "; target=" +target.nodeName+ "; it=" +it);
  14.             if( target.hasChildNodes() ){// if the element has childs we need to delete them first
  15.                 debug("+++++++node(" +target.nodeName+ ") has childs");
  16.                 cDestroyer( target );
  17.             }
  18.             if( target.id != "debug" ){ node.removeChild(target);}
  19.             debug("==End of " +target.nodeName+ " circle");
  20.         }
  21.     }
  22.     it--;
  23.     if( it > 0 ){
  24.         //debug(">>End of a big loop");
  25.         if( useSetTimeout == 1 ){
  26.             setTimeout(function() { cDestroyer(node,it) }, destroyTimeout * 1000);
  27.         }else{
  28.             cDestroyer( node, it);
  29.         }
  30.     }
  31.  
  32. }
  33.  
  34. function debug( msg ){
  35.     if( showDebug == 1 ){
  36.         container = document.getElementById('debug');
  37.         container.innerHTML = msg + "<br />\n"+ container.innerHTML;
  38.     }
  39. }
  40. function setSettings( which, val ){
  41.     if( which == "debug") {
  42.         showDebug = val;
  43.     }else {
  44.         useSetTimeout = val;
  45.     }
  46. }
  47. var destroyTimeout = 1;// in secs.
  48. var showDebug = 1;
  49. var useSetTimeout = 1;
Aug 18 '07 #3
jx2
228 100+
first of all
setTimeout() doesnt stop the script(you know that allready)
it "reminds" your script that it have to do some code after some time

in your case you should concsider to use setInterval() insted that would make the job
e.g.
[html]<a href="javascript:self.setInterval("cDestroyer()", 2000)">destroy</a>[/html]
(and do not use settimeout() of course)

what did happen in your code:
Expand|Select|Wrap|Line Numbers
  1. function cDestroyer( node, it ){
  2.     if( !node){ var node = document.body }
  3.  
  4.     var stuffToDestroy = node.childNodes;
  5.  
  6.     if( it ){ it = parseInt(it);}
  7.     if( !it ) { it= stuffToDestroy.length - 1;}// we start from the end of the dom tree
  8.     var target = stuffToDestroy[it];
  9.  
  10.     if( target ){// no " ... has no properties" error
  11.         if( target.nodeType == 1)//we need to delete only elements
  12.         {
  13.             debug("--node=" +node.nodeName + "; target=" +target.nodeName+ "; it=" +it);
  14.             if( target.hasChildNodes() ){// if the element has childs we need to delete them first
  15.                 debug("+++++++node(" +target.nodeName+ ") has childs");
  16. //===================== here is where the trubles starts ============
  17. //cDestroy will destroy "first child " yeah but after 1000 miliseconds
  18.                 cDestroyer( target );
  19. //========================================================
  20.             }
  21.             if( target.id != "debug" ){ node.removeChild(target);}
  22.             debug("==End of " +target.nodeName+ " circle");
  23.         }
  24.     }
  25.     it--;
  26.     if( it > 0 ){
  27.         //debug(">>End of a big loop");
  28.         if( useSetTimeout == 1 ){
  29.  
  30. //=========  thats where the first child will be destroyed next time   ======
  31. //========= see coments above ==================
  32. // ======== after 1000miliseconds but setTimeout() doesnt wait!!      ====
  33.  
  34.             setTimeout(function() { cDestroyer(node,it) }, 
  35.  
  36.  
  37.  
  38. destroyTimeout * 1000);
  39.         }else{
  40. //=================== but you do destroy parent here immeadietly after 
  41. //=================== you used cdestroy ( child ); ==============
  42.  
  43.             cDestroyer( node, it);
  44.  
  45. // ===now it keep doing the job but cDestroy( yourChild ) is waiting   =====
  46. //=== and after 1 second there is nothing to destroy because child 
  47. //=== was destroyed toghether with parent
  48.  
  49.         }
  50.     }
  51.  
  52. }
  53.  
  54. function debug( msg ){
  55.     if( showDebug == 1 ){
  56.         container = document.getElementById('debug');
  57.         container.innerHTML = msg + "<br />\n"+ container.innerHTML;
  58.     }
  59. }
  60. function setSettings( which, val ){
  61.     if( which == "debug") {
  62.         showDebug = val;
  63.     }else {
  64.         useSetTimeout = val;
  65.     }
  66. }
  67. var destroyTimeout = 1;// in secs.
  68. var showDebug = 1;
  69. var useSetTimeout = 1;
i hope i made it clear

post again if you get into truble

regards
jx2
Aug 19 '07 #4
si4
5
OK. Thanks a lot for the help.

I've though to use setInterval(), but I wanted to understand why this brakes.

Thank you again for the explanation!
Aug 19 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Jupiter49 | last post by:
I'm trying to move pictures around on the screen, with a slight delay between the first picture and second picture (following onmousemove). When I add the setTimeout function I must be doing it...
2
by: Gordan | last post by:
hi i want to have a "close" button that user can click but that will also "click itself after 10 sec" so heres what i did function auto_close(x) { if(x>0){ document.form.button.value="CLOSE...
3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
18
by: Frances Del Rio | last post by:
this code is supposed to flip imgs at intervals of one second, but it flipps them much faster, it seems it flips them all in that first second, the more seconds the faster it flips them, instead of...
2
by: Athanasius | last post by:
Could someone shed some light as to why the following setTimeout function will not work on the Mac IE5.2? It does however work on PC(Forefox,Netscape,IE) & Mac(Safari,Firefox). Here is the script,...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
28
by: Andre | last post by:
Hi, Does anyone know whether the ECMA, or an other standard document, specifies a maximum for the value that can be pass to the setTimeOut() function in Javascript? Andre
9
by: pengypenguin | last post by:
As we know, Javascript suffers an insufferable lack of a wait() or sleep() function, and so setTimeOut must step in to take up the slack. A function can use setTimeOut like sleep() by calling...
35
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.