Reputation: 317
I'm using ajax to check whether there is no new alerts stored in my sql database. I've set it to run every 30 seconds but instead it keeps on calling the function that checks the database every second. Here is my code.
This is code in the view. "_Tasks" is my partial view and it will be the view that is going to be updated. I haven't done anything for a success return because it never reaches that code.
@Html.Action("_Tasks")
<script type="text/javascript">
(function poll() {
$.ajax({
type: 'GET',
cache: false,
url: '@Url.Action("TasksRefresh")',
dataType: "json",
complete: poll,
timeout: 30000,
success: function (data) {
if (data.success == true)
alert("Hello");
}
});
})();
</script>
This is in the controller
public JsonResult TasksRefresh()
{
var alerts = getAlerts();
var cache = HttpRuntime.Cache["Tasks"];
if ( cache == alerts)
{
return Json(new
{
success = false,
});
}
else
{
return Json(new
{
success = true,
// View = this.Re
});
}
}
Upvotes: 2
Views: 1081
Reputation: 44740
timeout: 30000
is just to make sure that your ajax call would wait for response for maximum of that much time.
You are executing your poll function as soon as ajax call completes that is why calls are made so quick.
Upvotes: 0
Reputation: 121
What I can guess is, you are executing the poll function again on complete of the ajax call. It might just take a second to complete that ajax call.
You can use the timer at javascript code. try using settimeout
or setInterval
. And do ajax call in that timer. See if is helpful.
Upvotes: 1
Reputation: 17782
Try this:
(function poll() {
$.ajax({
type: 'GET',
cache: false,
url: '@Url.Action("TasksRefresh")',
dataType: "json",
complete: function () { setTimeout(poll, 30000); }, // Changed, call poll again when 30s has pasted
timeout: 30000, // This just says it fails if the request takes more than 30s
success: function (data) {
if (data.success == true)
alert("Hello");
}
});
})();
Upvotes: 3
Reputation: 17307
Timeout is not a delay. Timeout is how long it should wait before considering the request a failure. By setting complete
to poll
, you are telling it to immediately make another call. You need to put a delay in your complete
function.
Upvotes: 2