The sort of situation you describe generally results in a draw by one of two rules:
The first is the threefold repetition rule, which applies when the exact same game position is repeated three times. For example, if you and your opponent are each moving back and forth between the same two spaces, once you have come back to your starting position after two full loops, the game can be declared a draw.
The second is the 50-move rule, which applies when there have been no captures or pawn advances (irreversible moves) for at least 50 consecutive moves of white and black. This is invoked mostly in endgames where the board is very open and so it can take a very long time for (and be difficult to notice when) an exact position is repeated three times.
Of course, the game can end in a draw immediately if both players agree, which may cut these conditions short if it is obvious (for example) that the game is going to end in a perpetual check.