As this play approaches its denouement, the emotional intensity becomes almost overwhelming. Shakespeare understood that the audience needs a break at this point before the deaths of Gertrude, Claudius, Laertes, and Hamlet occur. The playwright offers this comic relief just prior to Hamlet's and Horatio's witnessing the funeral of Ophelia in a scene that is at once poignant and anger-filled. Laughter is the necessary outlet; this emotional discharge helps the audience prepare for the final, desperately tragic scene of the play.
There is only so much intensity an audience can take within a couple of hours' watching. With every death or battle, there must be some accompanying humor to release the tension and allow the audience members to relax a bit in order to prepare for the next intense murder or battle. In tragedies, a minimum of five people die...there are many more than that in Hamlet. In fact, the majority of deaths take place in the very next scene from this comic relief.
Shakespeare liked to insert a comic scene before a major event in his tragedies (Mercutio in the town square before Romeo and Tybalt fight, the gatekeeper in Macbeth who jokes with Macduff before Duncan's body is discovered, etc.). Act 5 is the act with the deaths of Gertrude, Laertes, Claudius, and Hamlet in them. Everything comes out into the open in this act which makes it of supreme intensity and importance.