Does anybody know why sometimes they border police stamp the passport while leaving the schengen and sometimes not?
Because some countries have decided that adding such a stamp serves no useful purpose, but others have decided instead to comply with the provision of the Schengen Borders Code that calls for such passports to be stamped.
The main purpose of the stamps is to record when the passport's bearer entered and left the Schengen area, which is primarily useful to determine whether the person has exceeded the 90/180 rule. But the 90/180 rule doesn't apply to people with residence permits in the country of residence, and there's no tracking when they travel between that country and other Schengen countries, so what's the point of stamping?
In a comment, you ask
If someone a national of third-party country (say India), has for example Italy temporary resident permit, can he stay in his own country more than 90 days in 180 days?
An Indian citizen can spend an indefinite amount of time in India. It's true that a residence permit can become invalid if the bearer is away from the country of residence for a certain amount of time, and passport stamps could be used to establish when someone was outside the Schengen area and therefore away from the country of residence, but other evidence would also be taken into account, so passport stamps are not particularly critical in that regard.