Jak*_*ner 14 javascript css animation angular
我们有一个Angular 2站点,其中有一个websocket泵送从后端到我们网格的数据.为了表明最近的更新,我们使用CSS来设置行的背景颜色,并在受影响的单元格上设置粗体字体.
该指示应该只持续很短的时间.
1)我们的第一次尝试是在下一批从服务器到达时重置所有指标.这样做效果很好,但在某些观点中,很少有更新,这意味着指标可以保持很长时间,这有点令人困惑.
如果更新指标在固定间隔(例如4秒)后消失,则会更加一致.
2)我们的下一次尝试是使用CSS动画.但过了一段时间,它已经落后很多了.给人的印象是,运行过多的动画会使浏览器超负荷,无法处理请求的时间.也许每个动画在后台都有自己的计时器?
3)第三次尝试是让一个计时器以固定间隔运行,然后检查要重置的记录.我们创建了一个定期检查到期项目的TimerService.将项添加到计时器池时,可以使用任意等待时间进行配置.
这有效,但在日志窗口中经常出现违规警告:
[Violation] 'setInterval' handler took 56ms
[Violation] 'setInterval' handler took 74ms
[Violation] 'setInterval' handler took 63ms
[Violation] 'setInterval' handler took 88ms
...
Run Code Online (Sandbox Code Playgroud)
但是当我们计算checkItems方法中发生的事情时,它只需要0.03ms!
我们都有C#背景,并且刚刚与Angular合作了几个月.也许我们正在强制实施后端方法?
我们错过了上下文切换吗?
是否有更多前端友好的方法?
我们可以对代码进行一些重要的优化吗?
所有建议表示赞赏!
以下是建议的TimerService导致所有警告:
import { Injectable, OnInit } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { Subject } from "rxjs/Subject";
@Injectable()
export class TimerService {
private timerItems: TimerItem[] = [];
private dueTimeReachedSubject: Subject<string> = new Subject<string>();
public dueTimeReached: Observable<string> = this.dueTimeReachedSubject.asObservable();
constructor() {
setInterval(() => this.checkItems(), 1000);
}
private checkItems() {
let now = Date.now();
let removeKeys: string[] = [];
this.timerItems.filter(t => t.dueTime <= now).forEach(t => {
this.dueTimeReachedSubject.next(t.key);
removeKeys.push(t.key);
});
this.timerItems = this.timerItems.filter(t => removeKeys.indexOf(t.key) < 0);
}
public add(key: string, delayInSeconds: number) {
let dueTime = Date.now() + delayInSeconds * 1000;
let timerItem = this.timerItems.find(t => t.key === key);
if (timerItem) {
timerItem.dueTime = dueTime;
}
else {
this.timerItems.push(new TimerItem(key, dueTime));
}
}
public remove(key: string) {
this.timerItems = this.timerItems.filter(t => t.key !== key);
}
}
class TimerItem {
constructor(public key: string, public dueTime: number) { }
}
Run Code Online (Sandbox Code Playgroud)
编辑
我试图使用Observable.interval:相同的结果与完全相同的警告消息:"[Violation]'setInterval'处理程序花了xx ms"
我尝试使用setTimeout重复调用:结果相同,但修改了警告消息:"[Violation]'setTimeout'处理程序占用了xx ms"
我甚至试图清空每一行的checkItems,我仍然得到警告.
警告是从zone.js中抛出的,似乎是一个Angular内部推荐.我知道我可以关闭Chrome开发人员工具中的详细日志记录,但我经常使用console.debug进行开发,这意味着它们也会消失.
警告是可以的,我想对于慢速函数,但在这种情况下它只是触发一个setInterval函数.为什么会这么慢?
您确定在清除 checkItems 中的代码后重新构建了项目吗?
另外为了以防万一,我在这里设置了一个 StackBlitz
使用您的代码,无法重新创建它..
如果您仍然遇到问题,也许您可以分叉 StackBlitz 并尝试在那里重现问题?