Then Judah told his daughter-in-law Tamar, “Go to your father's house and live there as a widow until my son Shelah grows up.” For he thought, “Maybe he'll die too, just like his brothers.” So Tamar went and stayed in her father's house.
Onan realized that any children he had wouldn't be his own, so whenever he slept with his brother's wife he made sure she wouldn't become pregnant by withdrawing and spilling his semen on the ground. In this way he prevented any children being born on behalf of his brother.
When two brothers live near to each other and one of them dies without having a son, the widow is not to marry a stranger outside the family. Her husband's brother is to marry her and sleep with her, fulfilling the requirements of a brother-in-law to provide her with children.