1

I am new to webworker but I managed to send xmlhttprequest to my rest api and I got json back. But I want send this request again and again (in a loop), until the page is active. I actually want to show values in real time. I want to make a simple web application in which when data is inserted in database my webworker should show that data without refreshing the page. Is there any better way to do so. Kindly help me in it. sorry for bad English.

Ans Bilal
  • 987
  • 1
  • 10
  • 28
  • Are you making `POST` request to server? – guest271314 Feb 28 '17 at 15:23
  • 1
    This seems like it would be perfect for [web sockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) – George Feb 28 '17 at 15:24
  • I am making get request to server . I actually want to show some readings from my hardware(sensors) to the web. My hardware is storing data in database using post request to my api. web worker is also showing data using get request. But webworker only work once when i click the start button to start the worker. I want worker to continue send get requests and retrieve data until it is not stopped – Ans Bilal Feb 28 '17 at 15:29
  • As George said, use websockets. With web sockets, you can push from your server to the client instead of having to use long-polling (what is what you try now). – baao Feb 28 '17 at 15:46

1 Answers1

1

You can use EventSource to get stream from server until .close() is called at Worker, or message is passed to Worker signalling Worker to call .close().

const es = new EventSource("/path/to/server");
es.addEventListener("open", function(event) {
  console.log("event source open")
});
es.addEventListener("message", function(event) {
  // do stuff with `event.data`
  console.log(event.data);
});
es.addEventListener("error", function(event) {
  console.log("event source error", event)
});

button.addEventListener("click", function() {
  es.close();
});
guest271314
  • 1
  • 15
  • 104
  • 177