473,809 Members | 2,809 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

setTimeout() recursion problem

5 New Member
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 5226
jx2
228 New Member
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 New Member
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 New Member
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="javascrip t:self.setInter val("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 New Member
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
3076
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 wrong because the function that calculates the new coordinates for the picture returns 32 million and change instead of the coordinate. This causes the picture to not be able to appear on the display, obviously. Here's the calling code (snipped...
2
17283
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 (auto close in "+ x +" sec)"; x--;
3
14962
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) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
18
2209
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 the other way around... (I mean it seems to me the more seconds I put in there the more seconds should go by betw. flips... each photo is in a div, each div has a z-index of 0, 1, 2, etc..) http://www.francesdelrio.com/cassini (pls reload a...
2
4680
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, it should simply present an alert message after 5 seconds. Thanks. <html> <head> <script language="javascript"> function MsgTimer() { var self = this;
12
5560
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. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
28
5315
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
6728
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 itself after x seconds. This begs a few questions: Is this design building enormous calling stacks to nowhere? Will the users machine eventually run out of memory space to contain this stack? How can this be avoided? Thanks, -- Whit Nelson
35
4745
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
9602
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10639
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10120
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7661
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.