user16214473
user16214473

Reputation:

JavaScript automatic refresh

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();
});

Upvotes: 0

Views: 70

Answers (2)

Elias Soares
Elias Soares

Reputation: 10264

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.

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 252

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);

Upvotes: 0

Related Questions