Escape is not guaranteed however; whether the player is successful at running away from the battle is determined by a calculation involving the speed of the combatants.

It involves speed and an escape formula.

Escape formulas:

For Gen 1 and 2:

>Under normal circumstances, the chance of escaping is determined by the formula Escape

, where

A is the current Speed of the player's active Pokémon,

B is the opposing Pokémon's Speed divided by 4, mod 256, and

C is the number of times the player has tried to escape during the battle (counting the current attempt). If player's Pokémon attacks, this number is set to 0.

If F is greater than 255, the player escapes automatically. Otherwise, a random number is generated between 0 and 255. If that number is less than F, the player escapes. If not, the escape fails and the player's Pokémon does not make a move that turn. If B is equal to 0, escape is automatically a success.

For Gen 3 and 4

>Under normal circumstances, the chance of escaping is determined by the formula , where

A is the unmodified Speed of the player's active Pokémon,

B is the opposing Pokémon's umodified Speed

C is the number of times the player has tried to escape during the battle (counting the current attempt).

The result is mod 256.

A random number is generated between 0 and 255. If that number is less than F, the player escapes. If not, the escape fails and the player's Pokémon does not make a move that turn. If B is 0, it's set to 1.

Basically, it has to do with speed.

Hop I helped!

Source