JS centering

by karim79

HTML

<div id="viewport">
    <img id="myImg" src="http://static.php.net/www.php.net/images/php.gif"/>
</div>

CSS

#viewport {
    position: relative;
    max-width: 600px;
    max-height: 600px;   
    width: 100%;
    height: 500px;
    background-color: slategray;   
}

#myImg {
    position: absolute;
}

JavaScript

var $view = $("#viewport"),
    $i = $("#myImg"),
    resizing = false,
    redrawsPerSecond = 5;


// horizontally and vertically center
var t = false;

var centerImage = function($img, kill) {
    console.log("centerImage() called");
    $img.stop().animate({
        marginLeft: ($view.width() / 2) - ($img.width() / 2) + "px",
        marginTop: ($view.height() / 2) - ($img.height() / 2) + "px"
    }, "fast");

    if (kill) {
        
        clearInterval(timer);
        clearTimeout();
        timer = false;
        return;
    }
    t = setTimeout(function () {
        clearInterval(timer);
        timer = false;
        centerImage($i, true);
        
    }, 1000);
};

centerImage($i);

var timer = false;

$(window).on("resize orientationchange", function() {

    if (!timer) {
        timer = setInterval(function () {
            
            centerImage($i);
        }, 200);
    }
});

//console.log(Math.floor(1000 % redrawsPerSecond));