0

it's my first time with JS and I'm doing task for my class. How can I set automatic refresh every n seconds in this type of code? Found some examples but none of them worked for me.

var http = require('http');
var port = 8080;

function lightSensor() {
   var data =  Math.random().toFixed(2)
   console.log("Light sensor: " + data);  
   return data;
}

http.createServer(function(req,res){
  res.writeHeader(200, {'Content-Type': 'application/json'});  
  res.write('{"Light sensor" : ' + lightSensor() + '}');      
  res.end();
}).listen(port);
console.log('Server listening on: http://localhost:' + port);

process.on('SIGINT', function () { 
  process.exit();
});

2 Answers2

1

Ant kind of delays inside an http request are not desirable.

Actually, you need to modify where you call this http server to repeat the http request every n seconds.

For example if you are calling this in JavaScript (inside a browser or nodejs) you can use setInterval to repeat the call:

setInterval(() => {
  fetch('localhost').then(res => console.log(res))
}, n * 1000)

Note that if the interval is lower then your server response time, the order of the output might not be the same as the requests. If you need to wait for the previous response before doing another request, you must use some more complex code to wait the previous request.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59
0

You can use setTimeout javascript function for this. eg. If you want to call lightSensor function in very 5 sec then use below code -

setInterval(lightSensor, 5000);
Amit Gupta
  • 252
  • 3
  • 8
  • Why does this help here? the res has already been sent by that point? May you share an example using the code from the question? – evolutionxbox Jun 13 '21 at 12:34
  • There must be some code that you need to call every n second, right? Then call that function from setTimeout – Amit Gupta Jun 13 '21 at 12:36
  • (I am not the OP) - Why does calling `lightSensor` help here? It may call the function again, but the page has already been sent back to the browser. – evolutionxbox Jun 13 '21 at 12:40
  • 1
    setTimeout executes function only once after the specified time you have to use setInterval @Amit Gupta – Uzair Saiyed Jun 13 '21 at 12:43
  • Then your question and code given is incomplete, you need to give the complete detail. When http.createServer called? Which function you need to call in every n sec? – Amit Gupta Jun 13 '21 at 12:44
  • @sowiacz may you answer Amit's comment? – evolutionxbox Jun 13 '21 at 12:47