Reputation: 1213
I am having trouble the following javascript. I am using the jQuery framework.
This code works the first time, displaying the date, temperature and humidity corectly but the second time it runs i get this error message;
Uncaught SyntaxError: Unexpected identifier
Here is the code;
var gettingTemperature = $.post("/get_temperature.php");
setInterval(gettingTemperature, 5000);
gettingTemperature.then(function (data) {
$('#date').text(data.date);
$('#temperature').html(data.temperature + "℃");
$('#humidity').text(data.humidity + "%");
}, function () {
console.log('Unable to access temperature model');
}
);
Upvotes: 1
Views: 3067
Reputation: 12606
You are supposed to pass a method into setInterval
, but you are passing a promise. Usually in this scenario you would just pass the success or fail function into the $.post
call, but if you really need to use the promise, then that's fine too. Since you don't know exactly when the $.post
call will return (i.e. how long it will take), you shouldn't be using setInterval
, because if it takes longer than the interval, you could end up with multiple concurrent requests, and that isn't very useful.
What most people do in this scenario is to wait until the first $.post
requests finishes, then in the complete
handler, call the $.post
again. That way you will only ever have one request out at a time.
Upvotes: 1
Reputation: 16564
gettingTemperature
doesn't represent the call to $.post() but rather the result of calling $.post() which is the jqXHR object
setInterval expects a function reference as a first parameter but you hand over the jqXHR object. That's why you run the $.post() once (with the very first line) and setInterval fails
var gettingTemperature = function {
$.post("/get_temperature.php").then(function (data) {
$('#date').text(data.date);
$('#temperature').html(data.temperature + "℃");
$('#humidity').text(data.humidity + "%");
}, function () {
console.log('Unable to access temperature model');
});
};
gettingTemperature();
setInterval(gettingTemperature, 5000);
Upvotes: 4