JavaScript’s setTimeout and how to use it with your methods

Update (May 2015): The following article deals with the nowadays well know JavaScript scope behavior and it’s much better explained/solved elsewhere.

While working on real time web chat application I run into problems with JavaScript’s setTimeout function. I would like to write down what I learned. It may save you some time, next time you’ll need to use this function.

Shortly about setTimeout

setTimeout is a simple JavaScript function used to repeatedly call some function after a specified amount of time. It takes two required parameters and an unspecified number of optional ones. Like this:

setTimeout(functionToCall, time, param1, param2, ....);functionToCall is the name of the function which will be called after time millisecond. You either use reference like in the example above or a string representing a call to the function:

setTimeout('functionToCall()', time, ...)The optional parameters can be used to pass any number of parameters to our functionToCall.

Where’s the catch?

Everything works as expected until you try to call a method inside your ‘class’ (there are no real classes in JavaScript). Something like this won’t work:

setTimeout(this.methodToCall, time);Passing a string representation instead of reference doesn’t work either.

The solution

I found the solution after a while searching in Google Code Search. The above example needs to be rewritten like this:

setTimeout(function(thisObj) { thisObj.methodToCall(); }, time, this);Here we are passing reference to our class as an optional parameter of the setTimeout function. In the called function we catch it and suddenly we can use it to call our method. I have no idea why such a simple thing needs to be so complicated but it only demonstrates that you need to learn a few tricks when you want to do real OOP in JavaScript.

Update

When you leave your blog not-so-very-updated for some time you’ll start to notice some bad things. Traffic slowly declines and the more you don’t post the lazier you are to write something new. But I don’t want to talk about that.

I made quite a big decision lately – I left the college (willingly). My main reason was that I was, with time, more and more interested and occupied by my freelance career. It escalated to such a point that I had to make a decision. Stay in the school or left and fully concentrate on my business. I chose the later. There was no reason for me to stay – I was simply bored in school. There was very little useful knowledge that I was gaining there. Our programming classes, the only ones that I enjoyed at least a bit, became a joke in the 3rd semester. But I don’t regret my time spent there. I met a lot of great people and learned something too.

I am quite excited. Finally I can concentrate on things that I really enjoy doing. I am confident that this is the right way for me to go, but, well, time will tell.

CakePHP and WebBaker

Recently I started using this wonderful PHP framework called CakePHP. It really moves the whole web development process to another level. It has got the MVC pattern, great community, good documentation, lots of people writing about it and there is the WebBaker. WebBaker is a PHP script that let’s you easily create all the files you need for your MVC pattern (model, controller, views). This saves you a lot of precious minutes.

Webbaker in action The CakePHP and WebBaker combination is deadly. You can have a functional element in your site like in 1 minute. All you need to do is create a table in the database and use WebBaker to generate appropriate files. At this point when you have written exactly 0 lines of code you have a fully functional interface where you can list, view, edit, add and delete items from database. This is possible due to the excellent scaffold functionality build in Cake. Then you can start writing your own code and smoothly replace the scaffolds. Try it, you’ll never want to go back.

Trying out Ubuntu

I am happily moved to my new home for more then two weeks now. I was both lazy and occupied to write something. But right now I have a good reason. I bought a new hard drive and guess what? I installed Ubuntu on it to dual boot with Windows. It was not that new to me, because I was playing with Ubuntu before but that changed when I installed XGL and Compiz. I was simply amazed. In the area of 3D accelerated user interface Compiz can not be compared to XP not even Vista. Take a look at this video but you really have to experience it first hand to see the potential. One thing however still keeps me from using Ubuntu for my everyday work. Font displaying. Clear Type is so much better that everything that can be set up in Ubuntu (yes, I tried various guides how to make this better). This really is important to me because texts are the thing I look most at when behind a computer and they have to be as smooth as possible. So I’ll probably stay with Windows for some more time, but I feel it won’t be for long.

Moving to a new flat

The summer holidays officially ended for me. Tomorrow I am moving to a new flat in Bratislava where I study. The school is starting around the 18th of September but there are some things that needs to be done there before. I will be offline for a few days, until my provider connects me. This will be terrible but I survived two weeks on vacation during the holidays without the net so I know how it is like 🙂 I have some articles started and I hope I’ll finish them during this time. Stay tuned!

Breaking the 200+ unique visitors a day!

233 unique visitors On Wednesday I had 233 unique visitors! It’s a great feeling. That’s the best number I have got in my short blogging career so far. It’s nothing breathtaking but it really motivates me to write more quality content. Not that the CSS Debugging Tips (posting this on dzone caused it) was some masterpiece, but there are surely people that profit from reading it. So thanks everybody and off I go to write something worthy 🙂

Books I read recently

I would like to share some great books I have read recently or I am reading right now. If you have something to do with the subjects mentioned here I definitely recommend these.

PHP 5 Power Programming

PHP 5 Power Programming You think you know PHP? Maybe after reading this book you’ll change your mind. This is an extensive journey trough PHP 5 written by the people who know it best. There are a lot of useful code examples and the whole thing is quite amusing to read. The book passes 1 Million downloads so far and they estimate that 1 in 5 PHP developers have this book. Not convinced yet?

Code Complete (second edition)

Code Complete Everyone who ever touched some production code should have this one. This book covers everything from application design to naming conventions. Every page offers pragmatic insight gained through years of effective coding experience and continues to be the principal handbook of software construction success for its practitioners. Project leaders should read this book cover to cover, and then purchase a copy for each of their direct reports. You probably have at least heard of it. This is a must.

The Zen of CSS Design

Zen of CSS Design Another bestseller. For everyone who does web design. The last chapter really nails it. The CSS development of 5 designs from CSS Zen Garden is explained here step by step. I learned a lot from this one.

iBox

Ahmed Farooq saw my posts about Ligthbox and ThickBox image displaying solutions and send me an email that he develops something similar which is definitely worth mentioning.

iBox weights just 11 kb and supports image displaying and various other types of content, like HTML code. It has got a few useful configuration options that you can embed directly into the links. One big advantage is that the script is self-contained, so it would not conflict with other libraries you might include.

So if you want to say goodbye to the old school JavaScript pop-up windows, you have plenty of alternatives to choose from. Lightbox started it all, ThickBox is my personal favorite and iBox has the potential to outrun them both. Try them all and choose one that best suits your project.

Update (May 2015): Links removed, as they no longer work 🙁

CSS Debugging Tips

If you have some experience with CSS layouts you probably know the feeling of hopelessness when you are staring at some box overlapping something it shouldn’t and so on. You tried dozens of possible rules combinations that came to your mind but nothing helps.

Over time I gathered some simple techniques that help me to deal with CSS problems much easier and straightforward. If you aren’t new to web design you for sure know or use some of them.

Proper tools

First you should have the proper tools that will help you with common tasks like validating your document: Everybody knows Web Developer Toolbar for Firefox. Then there is the Web Developer Toolbar for Opera and one for Internet Explorer from the IE team too. Since you should test your pages in all of these browsers (at least on Windows platform) it’s good to have the same functionality in all of them.

Recently a browser called Swift has been released. It’s based on the WebKit rendering engine which Safari on Mac uses. This is invaluable for testing your sites on your Windows box. So go ahead, download it and start testing your pages with it too.

What can you do in your stylesheets

Let’s start with some tips. Note that you are not going to delete the actual styles for the area you are working on. You just add these to determine where exactly the problem lies. The big advantage here is that you can determine the error quickly.

Outline them all

html body #something * {
border: 1px solid Red;
}

Using the border rule with * Add a border (of your favorite color) to all the elements nested in #something. Note you are using such a specific selector that this style will overwrite all the other ones. This quickly gives you an understanding of what exactly are the sizes and positions of all the elements in the area. From my experience with this you can reveal like 80% of all the problems. Just don’t forget to remove it when fine tuning. Remember border adds to the resulting width of the element.

No margins please

html body #something * {
margin: 0;
padding: 0;
}

This is invaluable when you think you have some padding or margin doing mess in your layout (and this is a very common problem). It resets the margins and paddings to 0 in all the elements nested in #something. If the problem does not disappear you know the margins and paddings are not the cause and you should look elsewhere.

As you can see the universal selector * is very useful. You can reset any setting like this across the desired area. With this technique you identify the rule which is causing problems in no time. Then you can take the proper action.

More Than Fest 2006

MTF 2006 Tomorrow I am leaving for More Than Fest at Ružiná, Slovakia. This will probably be the biggest metal meeting to date in this country. It will be crazy 🙂 Maybe I will make some photos with my ultra great cell phone camera. I will be there for three nights, we will sleep in a tent. Hope the weather will not disappoint us.

Regarding the bands, I am looking forward to Gamma Ray and Behemoth. I saw Gamma Ray 3 times to date and I always had a great time. Behemoth is currently one of the best known Poland metal bands. I hope we will see why.