All NPCs that are not Town NPCs are subject to despawning when outside a certain maximum distance from the player.
All players in a world have two rectangular regions centered around themselves that govern this process. The outer rectangle, referred to here as the Active region, measures 504 blocks wide by 283.5 blocks high, the width and height of a 1920x1080 screen multiplied by 4.2 in both directions. While outside the region, if it isn't a boss or something special (such as a worm head), it will instantly despawn. While inside this rectangular region, NPCs that are capable of despawning will be considered active for the player and will be counted when spawning NPCs. Do note that being active doesn't exempt an NPC from being despawned.
The inner rectangle, here referred to as the Timer region, is considerably smaller at 120 blocks wide by 67.5 blocks high, equal to a 1920x1080 screen region plus the size of the entity. While an NPC is outside this region, a timer begins to count down for a period of time (by default it is 750 ticks, or 12.5 seconds, but there are a lot of exceptions); when it reaches zero, the NPC will despawn, no matter whether it is counted as active. Reentering a player's Timer region will reset this timer, meaning that NPCs that remain within this region will never despawn. Segments of a larger entity, such as the Eater of Worlds, are not subject to these timers as long as the head remains active.
- A tick is a time unit countable by the software. Most of Terraria's updating logic happens every tick. A tick has the length of 1/60th of a second, hence there are 60 ticks in a second and 3600 ticks in a minute.