Skip to main content

Posts

Showing posts from August, 2011

Sleep sort in JavaScript and closures

     There is this "genius" sorting algorithm called " sleep sort ". I don't know what came to my mind, but I decided "let's do it in javascript!". I thought that it won't take more than 2 minutes. Starting with such wrong and over confident assumption, it was a journey into the details of javascript which I had never bothered to pay much attention to. I learnt quite a few things on the way and will share the same in this blog.      Here is the code which I wrote off : 1 2 3 4 5 array = [1, 9, 4, 8, 2, 3, 6]; for (i = 0; i < array.length; i++) { window.setTimeout ( "console.log(array[i])" , array[i]*1000); }         What the code was supposed to do was, for each integer in the array, wait for those many seconds and then print that integer. So, the integer 9 will be logged into the console after 9 seconds while the code will log 2 into the console after 2 seconds.       Here is what it logged into the conso