gpt4 book ai didi

javascript - 提高性能每秒刷新项目

转载 作者:行者123 更新时间:2023-11-28 06:48:11 26 4
gpt4 key购买 nike

我有一个 API,它可以每秒通过服务器发送事件 (SSE) 发送我的项目的更新。

基本上,我有一个集合$scope.items,其中包含大量信息,并且该列表中的每一秒都会更新一个项目。

我正在做的是:

  var source;
if (!!window.EventSource) {
source = new EventSource('/updates');
} else {
alertify.error('SSE not supported');
}

// Emit SSE for items
source.addEventListener('items', function (e) {
var data = JSON.parse(e.data);
$timeout(function () {
var item_index = _.findIndex($scope.items, function (item) {
return item.id === data.id;
});
var status = data.status;

if (item_index > -1) {
if (status === 'cancelled') {
$scope.items.splice(item_index, 1);
}
$scope.items[item_index] = data;
$scope.$apply();
} else {
$scope.items.push(data);
}
});
}, false);

我想知道我做得是否正确,或者我是否可以改进此代码,因为当我开始每秒循环很多很多项目时,应用程序非常慢......

最佳答案

查看您的代码:

var item_index = _.findIndex($scope.items, function (item) {
return item.id === data.id;
});

我担心每次访问 item_index 时都会进行完整搜索

我会定义一个函数:

  function getIndex(data){
_.findIndex($scope.items, function (item) {
return item.id === data.id;
});
};

并从您的内部调用它

$timeout(function () {
var item_index = getIndex(data);
...

关于javascript - 提高性能每秒刷新项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33212957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com