Q:

Consistently get data from action in controller with in MVC $.ajax()? 

I have this code in my controller:
int number = 0;

    public JsonResult JsonData()
    {
        for (int i = 0; i < 21; i++)
        {
            number += i;
            return Json(number, JsonRequestBehavior. AllowGet);
        }
        return Json(number, JsonRequestBehavior. AllowGet);
    }

And loop with jQuery Ajax script in the view:
<script type="text/javascript">
var tag = true;
$(document).ready(function () {
    while (tag) {
        $.ajax({
            url: "@Url. Action("JsonData", "Home")",
            dataType: 'json',
            success: function (data) {
                console.log(data);
                $('#counter').html('');
                $('#counter').html(data);

                if (data == 20) {
                    tag = false;
                }
            }
        });
    }
});
</script>

<div id="counter"></div>

My goal is to make jQuery Ajax to constantly get "number" from action "JasonData" and print that number to "DIV tag" But my current code is not working for some reason, - the result is that browser window will not stop loading if i'm using "while()" loop, if I'm not using "while()" loop it only prints the first value of "number" variable. 

A:

Use a setInterval/setTimeout instead of while loop, because continuously running script will block the UI and you can utilize the callback mechanism instead. 
$(document).ready(function () {
   var interval = window.setInterval(function(){
        $.ajax({
            url: "@Url. Action("JsonData", "Home")",
            dataType: 'json',
            success: function (data) {
                $('#counter').html(data);
                if (data == 20) { //<-- make sure data has value 20 and is not an object or anything
                    window.clearInterval(interval);
                }
            }
        });
    }, 1000); //<-- Give interval in milliseconds here
});

Demo
Or with timeout:
$(document).ready(function () {
  makeAjaxCall();
});

  function makeAjaxCall(){
         $.ajax({
                url: "@Url. Action("JsonData", "Home")",
                dataType: 'json',
                success: function (data) {
                    $('#counter').html(data);
                    if (+data < 20) {
                        window.setTimeout(makeAjaxCall, 1000); //Duration in ms
                    }
                }
            });
        }

Demo

