Javascript中的守护程序线程 [英] Daemon Thread in Javascript

查看:131
本文介绍了Javascript中的守护程序线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,该程序使用getJSON从服务器获取JSON并处理此数据并将其呈现给用户。但是服务器上的数据经常更新。如何每隔5分钟获取新的JSON并将其显示给用户并在后台线程中执行?我可以为此使用setTimeout吗?

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?

谢谢!
Matt

Thanks! Matt

推荐答案

使用每5分钟触发一次的时间间隔是一种显而易见的方法(也是与浏览器兼容的方法)。

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

这不会创建单独的线程,而是这样做的传统模拟。实际发生的一切只是将异步事件排队,并在尽可能接近规定的时间执行。但是,不能保证精度,因为它运行在同一线程上,因此在JS引擎的执行中需要一个机会之窗。

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.

JS引擎将尽力在所需的时间执行您的代码,但前提是可以免费执行。

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.

网络工作者脚本

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

(请注意,我在此处使用香草JS,而不是jQuery,因为我不知道如何使用您可以导入脚本,但是jQuery引用窗口,这会导致Web Worker中的错误,因为它们与窗口或DOM没有任何关系

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

主要JS脚本

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

每5分钟打电话给新工作人员是否有好处,或者像我所说的那样使用一次工作人员,是否每5分钟执行一次操作,我不确定。可能不是很多,因为在任何一种情况下,都有一定的间隔。

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.

这篇关于Javascript中的守护程序线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆