Daemon Thread in Javascript

2019-07-23 15:58发布

问题:

I have a program that gets a JSON from the server using getJSON and processes this data and presents it to the user. But the data on the server is being updated every so often. How can I get the new JSON every 5 minutes and display it to the user and do it in a background thread? Can I use setTimeout for this?

Thanks! Matt

回答1:

Using an interval that fires every 5 minutes is the obvious (and most browser-compatible) approach.

This does not create a separate thread, but is the traditional simulation of doing so. All that actually happens is the asynchronous event is queued up, to be executed at a time as close as possible to the point when you stipulated it should run. Precision is not guaranteed, though, because it's running on the same thread, so it requires a 'window of opportunity' in the JS engine's execution.

In other words, the JS engine will do its best to execute your code at the required moment, but only insofar as it is free to do so.

If you don't mind about older browser support, you could use a web worker, which genuinely does run on a separate thread.

web worker script

self.addEventListener('message', function(evt) {
        var gateway = new XMLHttpRequest();
        var intie = setInterval(function() {
        gateway.open("GET",evt.data.load_url,true);
        gateway.send();
        gateway.onreadystatechange = function() {
            if (gateway.readyState==4 && gateway.status==200)
                self.postMessage(gateway.responseText);
        }
   }, 300000); //every 5 minutes
}, false);

(Note I use vanilla JS there, not jQuery, as I'm not aware of any way of using jQuery inside web workers. You can import scripts, but jQuery references window, which errors in web workers as they do not have any ties to the window or DOM)

Main JS script

var worker = new Worker('worker.js');
worker.addEventListener('message', function(evt) {
    //the loaded JSON data is now held in evt.data
    alert(evt.data);
}, false);
worker.postMessage({load_url: 'json.txt'});

Whether there's any benefit in calling a new worker every 5 minutes, or, as I have, using one worker and having it act every 5 minutes, I'm not sure. Probably not a lot in it since, in either case, there's an interval going on.



回答2:

Yes, you can pull the data with setTimeout (or setInterval if you want it to run endlessly). I think it's your better option...