It works like this (in theory*): once the ball is across halfcourt, the guy with the ball can only stand there for five seconds if he's closely guarded, closely guarded meaning there's a defensive player within six feet of him. He can reset the count by starting his dribble if he hasn't already, and reset it again by picking up his dribble. If he's already picked up his dribble, he has to shoot or pass it within five seconds. If the ref counts five seconds without the player doing any of that, it's a violation and a turnover.
If you watch the ref when a player brings the ball up, he'll do a little chopping motion to the side with one hand- that's the count. If he puts both arms out in like a T motion, that means the count has been broken because the defender's not within six feet. If he starts counting with his other hand, that means the count has been reset (the player has picked up/started his dribble). Five chops in a row equals a violation.
*I say in theory because refs usually have stricter definitions of "closely guarded." In reality, you have to be almost touching the ballhandler to get the ref to start the count. The rule says six feet, but in practice they'll only call it if you're about three or four feet or closer.