Reputation: 11966
I have a silly page where a link will trigger a POST request for a long running task. So the page will have to poll another endpoint for status. Here is the actual code:
<script type=text/javascript>
function check_status(id) {
alert(id)
}
$(function() {
$("a#save_preview").bind('click', function() {
$.post($SCRIPT_ROOT + "/api/v1.0/creatives/" +
$("img#preview").attr("creative_id"),
{}, function(data, status) {
alert(status);
setTimeout(check_status(100), 8000);
}, "json");
});
});
So the stubbed check status is supposed to be called 8 seconds after the POST request succeeded. However, whenever I run this code, it's called right afterwards. What did I do wrong?
Upvotes: 0
Views: 238
Reputation: 25797
You have to provide a callback function to the setTimeout
method but instead of providing it, you are directly calling it check_status(100)
, so nothing is actually getting called after timeout. You can change in this way:
setTimeout(function() {
check_status(100)
}, 8000);
Upvotes: 1
Reputation: 4469
The line setTimeout(check_status(100), 8000);
should be setTimeout(check_status, 8000, 100);
or perhaps use an anonymous function if you need to support below Internet Explorer 10 like setTimeout(function(){check_status(100);}, 8000);
.
Upvotes: 3
Reputation: 7289
try to have a function inside setTimeout The below code should work in your case
<script type=text/javascript>
function check_status(id) {
alert(id)
}
$(function() {
$("a#save_preview").bind('click', function() {
$.post($SCRIPT_ROOT + "/api/v1.0/creatives/" +
$("img#preview").attr("creative_id"),
{}, function(data, status) {
alert(status);
setTimeout(function(){check_status(100);}, 8000);
}, "json");
});
});
Upvotes: 0