StuiterSlurf StuiterSlurf - 1 year ago 88
Javascript Question

What does this code using typeof … != "undefined" and clearInterval do?

For school I need to write a game in JavaScript but the problem is I don't understand what this part of code means:

if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, 60);

Answer Source

if (typeof game_loop != 'undefined')

if the variable game_loop is not undefined


clear the existing interval whose id is game_loop

game_loop = setInterval(paint, 60);

call paint every 60 milliseconds and store the interval id in game_loop.

Ideally for clarity the code would be written as:

if (game_loop !== undefined) {
game_loop = setInterval(paint, 60);

typeof xyz !== 'undefined' is used to avoid a possible bug when window.undefined is overridden, but no one should ever override window.undefined, so I wouldn't worry about it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download