Can do with recursive setInterval, or 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 in JSFIDDLE
But it is often better to do with recursive setTimeout, since we are making an external request sometimes some take longer than others and setInterval will already be defined even before the previous request has been finalized.
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 secondos to obtain answer, after 2 secs the second execution of the setInterval
is performed and only takes 1... And so on, this will result in atrocities and responses at the same time etc...
To ensure that the next request will always be made 5 secs (in this case) after we get an answer 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 in JSFIDDLE
are using jquery?
– Fábio