You can do with setInterval, or recursive setTimeout:
With setInterval:
<p id="temp"></p>
...
<script>
function loadTemp() {
alert('atualização');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("temp").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "https://thingspeak.com/channels/116346/field/1/last.html", true);
xhttp.send();
}
loadTemp();
setInterval(loadTemp, 5000); // aqui o tempo é em milisecondos, pus 5 secs só a titulo de exemplo... para 5 minutos seriam 1000 * 60 * 5 = 300000
</script>
Example on JSFIDDLE
But often it is better to do with recursive setTimeout, since since we are doing an external request some times take longer than others and setInterval will already be defined even before the previous request has been completed.
That is, suppose we have the setInterval in 5 seconds, this interval is always executed (5 secs), the first request was made and it took 3 seconds to get a response, in 2 secs the second execution of the setInterval
is performed and only takes 1 ... And from then on, this will result in hiccups and responses at the same time etc ...
To ensure that the next request will always be done 5 secs (in this case) after getting a response we do:
<p id="temp"></p>
...
<script>
function loadTemp() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert('successo no request');
document.getElementById("temp").innerHTML = xhttp.responseText;
setTimeout(loadTemp, 5000); // aqui o tempo é em milisecondos, pus 5 secs só a titulo de exemplo... para 5 minutos seriam 1000 * 60 * 5 = 300000
}
else if (xhttp.status >= 500){
alert('erro no request');
setTimeout(loadTemp, 5000); // aqui chamamos outravez no caso de falha, para a próxima pode ser que seja bem sucedida e atualize
}
};
xhttp.open("GET", "https://thingspeak.com/channels/116346/field/1/last.html", true);
xhttp.send();
}
loadTemp();
</script>
Example on JSFIDDLE