StuiterSlurf StuiterSlurf - 2 months ago 7
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

if (typeof game_loop != 'undefined')

if the variable game_loop is not undefined

clearInterval(game_loop);

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) {
    clearInterval(game_loop);
}
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.