A distraction technique used to combat insomnia.
Insomnia has probably always been with us. We have evidence of this particular technique, of counting sheep as they are imagined to jump over a fence, being used from 1854. That's from Seba Smith's Way down east; or portraitures of Yankee life:
"He shut his eyes with all his might, and tried to think of sheep jumping over a wall."