I'm currently working on my first ajax chat.
I built the basic view of the chat but i need some help understanding the best
way of retrieving new messages.

at first i tried checking for new messages each second to see if there are new messages from last second.
it worked fine but it did miss a few messages since it takes time to run the script therefore it's not a perfect 1 second.

Then i tried storing the last message id in the cookies
so it was checking for messages with a higher id, and updating the cookie with that last message.
but this time it was duplicating many of the messages since the script runs again before the previous one is done (it's alright with a high delay such as 1.5 seconds, but it's a problem if people have slow connection)

So what's the ideal way of checking for new messages?
Thank you.