# While loops

**URL:** <https://www.ruby-forum.com/t/while-loops/97803>\
**Category:** Ruby\
**Created:** [July 10, 2006, 6:04pm UTC](https://www.ruby-forum.com/t/while-loops/97803 "2006-07-10T18:04:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Erich\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/d78d45/32.png) [@Erich\_L](https://www.ruby-forum.com/u/Erich_L)\
**Post date:** [July 10, 2006, 6:04pm UTC](https://www.ruby-forum.com/t/while-loops/97803/1 "2006-07-10T18:04:30Z")

</div>

If I have this snippet of code for the main page that loads:

def index  
while 1  
logger.info(“hi”)  
end  
end

Then, I close the browser that opened that page, I notice that the  
logger continues to print “hi” to the file (using tail -f). Is there a  
way to stop the server from running such actions when the browser is  
closed? (The logger.info was just an example. It could be anything  
else)

Thanks

---

<div class="post-metadata">

**Author:** ![Erich\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/d78d45/32.png) [@Erich\_L](https://www.ruby-forum.com/u/Erich_L)\
**Post date:** [July 10, 2006, 6:43pm UTC](https://www.ruby-forum.com/t/while-loops/97803/2 "2006-07-10T18:43:47Z")

</div>

“Erich L.” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) writes:

> way to stop the server from running such actions when the browser is  
> closed? (The logger.info was just an example. It could be anything  
> else)
> 
> Thanks

When you close a page showing on the browser, the browser may or may  
not close the connection to your server. If it does not, then you  
can’t tell whether a page has been closed.

If it does, then you have to perform IO operation to detect the  
closing.

If you really care, you could surround the critical code with guard  
code that tries to detect connection closing (IO::select for  
read-readyness and performing IO#sysread(nonzero length) on such IO  
object returns a 0-length string).

But there is still no fool-proof way to detect a user closing a  
page. (Not even using javascript to handle window close event since  
that won’t be invoked when the browser is closed).

YS.

---

<div class="post-metadata">

**Author:** ![Erich\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/d78d45/32.png) [@Erich\_L](https://www.ruby-forum.com/u/Erich_L)\
**Post date:** [July 11, 2006, 3:38am UTC](https://www.ruby-forum.com/t/while-loops/97803/3 "2006-07-11T03:38:05Z")

</div>

I assume you are talking about a Rails app. index() should NOT run  
forever like that. It should generate the page and return. If you want  
to keep updating someting, “pull” information from the browser using  
JavaScript (make the while loop in JavaScript).
