在客户端处理大数据集
Handling large data sets on client side
我正在尝试构建一个使用 Server Sent Events 的应用程序,以便在 UI 上获取和显示一些推文(最新的 50-100 条推文)。
Url 上交所:
https://tweet-service.herokuapp.com/stream
问题:
- My UI is becoming unresponsive because there is a huge data that's coming in!
- How do I make sure My UI is responsive? What strategies should I usually adopt in making sure I'm handling the data?
当前设置: (为了更清楚地说明我要实现的目标)
- 目前我有一个 Max-Heap,它有一个自定义比较器来显示最新的 50 条推文。
- 每次发生变化时,我都会使用新的最大堆数据重新呈现页面。
我们不应该让 EventSource 保持打开状态,因为如果在短时间内发送了太多消息,这将阻塞主线程。相反,只要获得 50-100 条推文,我们就应该保持事件源打开。例如:
function getLatestTweets(limit) {
return new Promise((resolve, reject) => {
let items = [];
let source = new EventSource('https://tweet-service.herokuapp.com/stream');
source.onmessage = ({data}) => {
if (limit-- > 0) {
items.push(JSON.parse(data));
} else {
// resolve this promise once we have reached the specified limit
resolve(items);
source.close();
}
}
});
}
getLatestTweets(100).then(e => console.log(e))
然后您可以将这些推文与之前获取的推文进行比较,以确定哪些是新推文,然后相应地更新 UI。您可以使用 setInterval 定期调用此函数以获取最新的推文。
我正在尝试构建一个使用 Server Sent Events 的应用程序,以便在 UI 上获取和显示一些推文(最新的 50-100 条推文)。
Url 上交所:
https://tweet-service.herokuapp.com/stream
问题:
- My UI is becoming unresponsive because there is a huge data that's coming in!
- How do I make sure My UI is responsive? What strategies should I usually adopt in making sure I'm handling the data?
当前设置: (为了更清楚地说明我要实现的目标)
- 目前我有一个 Max-Heap,它有一个自定义比较器来显示最新的 50 条推文。
- 每次发生变化时,我都会使用新的最大堆数据重新呈现页面。
我们不应该让 EventSource 保持打开状态,因为如果在短时间内发送了太多消息,这将阻塞主线程。相反,只要获得 50-100 条推文,我们就应该保持事件源打开。例如:
function getLatestTweets(limit) {
return new Promise((resolve, reject) => {
let items = [];
let source = new EventSource('https://tweet-service.herokuapp.com/stream');
source.onmessage = ({data}) => {
if (limit-- > 0) {
items.push(JSON.parse(data));
} else {
// resolve this promise once we have reached the specified limit
resolve(items);
source.close();
}
}
});
}
getLatestTweets(100).then(e => console.log(e))
然后您可以将这些推文与之前获取的推文进行比较,以确定哪些是新推文,然后相应地更新 UI。您可以使用 setInterval 定期调用此函数以获取最新的推文。