Q:

What is the difference between animate and setInterval in my case

HTML
<div id="answer" style="width:100px;height:50px;">Answer></div>

JS
$(function () {
    var answer = $('#answer');
    var sizeChangerHandle;

    function setBackground() {
        sizeChangerHandle = setInterval(changeConstantly, 1);
    }

    function changeConstantly() {

        answerHeight = answer.height();
        answerWidth = answer.width();
        answer.width(answerWidth + 1);
        answer.height(answerHeight + 1);
        setTimeout(function () {
            clearInterval(sizeChangerHandle);
        }, 300)

        // I am only using one of these codes, either the above or the below! I comment the other one out when I use one.
        answer.animate({
            width: 400,
            height: 200
        }, 300);

    }

    setBackground();
});

I am trying to widen my DIV from being 100px wide to 400px wide and to have this take 300 split seconds. When I use the animate function, it works perfectly. The Div ends up 400px wide and it takes 300 split seconds. When I use the Intervals, the DIV stops its width at 176px. Why is this, it should really be running for 300 split seconds?  

A:

Your changeConstantly interval is not really firing once every millisecond. From MDN's notes on setTimeout:

Historically browsers implement setTimeout "clamping": successive setTimeout calls with delay smaller than the "minimum delay" limit are forced to the use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms...

The MDN page on setInterval confirms that this 4 millisecond restriction applies to setInverval as well.
Therefore, your interval function only runs 75 times (300 ms divided by 4 ms inverval), rather than 300 times. (Or, maybe it runs 76 times -- the last interval probably gets run just before the interval is cleared.)
The solution is to rewrite your code using an interval delay of no less than 4, and make your <div> grow by 4 times more during each iteration, i.e., use answer.height(answerHeight + 4);.

