Masturbation is grave matter.
It is a mortal sin if performed with full knowledge and deliberate consent.
If you have developed a habit, perhaps associated with something else that triggers it, you want to tell your confessor (ideally keep the same priest) that you have an addiction. This lowers your culpability.
Also you need to address the root causes (what triggers it? what situations cause it? what precedes it?) and avoid them. One can’t simply stop masturbating (unless you go the Origen route, which I sincerely discourage).
You also need to replace a vice with the opposing virtue, namely chastity. Learn more about it. Engage people who live chaste lives and reject promiscuity and dirty talk or dirty websites and movies. Read spiritual books and watch spiritual movies. There is a direct link between action, horror, and sex, so try to avoid the two if you don’t want to land on the third one. Laugh, watch funny things. And remember that it’s a normal part of life. Even the holiest saint went through puberty and felt sexual struggles.
The Catechism speaks of “a long apprenticeship in self-mastery”. It’s like becoming an Olympian, or an elite soldier. It does not happen overnight, it requires a strong will, and support from the Church (especially through the Sacraments, Adoration, and the Rosary). And above all, you must remind yourself that
- you are only trying to stay chaste for this one day
- you are powerless to do so, but there is a higher power, God’s power, that will enable you if you cooperate
These are principles at the root of many 12-step anti-addiction programs.