Shakespeare is known to add dark humor in his tragedy plays, especially in Hamlet. We see that in this play, Hamlet is going through so much in his life, with the sudden death of his father, then his mother remarrying with his fathers brother following the death of the King. That, as it is is something very hard to go through already. After he finds out the truth about his father, we see he becomes and acts crazy to get what he wants. He uses comic relief to release the tension of everything he has just found out and is going through.
He allows himself to act crazy and insults people so it may be excused. However, he knows what he is doing and speaks more with the truth; since people think he is crazy they do not give him much importance in what he says. In act II we see more comedy in what Hamlet says, especially in scene two. Me mocks what his mother and uncle have done. He uses this to relieve the tension of what has happened as he also tries to make it seem that it is not truly facing him, when in reality he is acting it out by his actions and words. He himself uses this comic relief to not let him truly effect him.