Timed events handler (frame rate control for games etc.)
This is a useful class module for games and some applications which need regular and precise update (music players, media players...). It basically allows you to set events happen certain times in a second. The timing is much more accurate than what you can get with a Timer control, it really does the best it can to ensure being on time.
Features:
Add any amount of timed events.
You can set several events with same ID and handle things by ID.
Efficiently prevents 100% processor usage. No freezing.
Lightweight: the only thing that could be really made faster would be to convert it to a normal module. I chose class module because it is easier to use and understand.
Skip processing if late: this is a must, because all computers might not be fast enough. You can see what happens when you try do 10000 updates a second for something that isn't lightweight.
I've included a sample project which shows a very basic use for the code.
How one would use this in a game?
Make one very often used event for checking controls, moving players, AI and other objects, detect collisions... (ie. trigger this code 240 times/second)
Screen update, drawing what is visible on the screen (for example 60 times/second)
Show information on frame rate (FPS) once in a second.
For code clarity, you might want to separate things to their own procedures instead of writing a long Main sub.
Important!
There are some rules that you should follow. You should avoid loops within loops, strings (especially if concatenations or coercions are involved), variants... anything that is even remotely slow. Even one slow thing can cause code to run very slowly if the code is repeated many times within a second.
Remember to compile your games with all advanced optimizations turned on! You'll see how much faster they can get