To turn on the self timer on the Nikon D40, go to the Custom Setting Menu (pencil icon). Go to item 4: Shooting mode.
Choose Self Timer to enable the self timer mode.
The wait duration of the Self timer can be set on a separate menu, this is item 16: Self-timer.
You can choose between 2, 5, 10 and 20 seconds.
2 seconds is useful when taking photos at night, you can press the shutter and take you hand off to prevent camera shake by pressing the shutter. 10 seconds is the classic time needed to press the shutter and run back to join your friends. 20 seconds is better if you have to run a long distance!
Read about the Nikon ML-L3 Remote Control to see how you can avoid all this running!