[英]Am I using setTimeout in an inefficient manner?
我有一個棱角分明的應用程序,我想實現“ Time Ago”功能。 如果我提出一些瘋狂的“問題”,這是一個壞主意嗎?
如果您能想象有一條Facebook帖子,上面寫着“大約在一分鍾前發布...”,那就是我的目標。
假設用戶從未刷新過頁面,而是從信號中心將問題附加到角度模板
export interface IQuestion {
timeAgo: string;
}
export class Question implements IQuestion {
public timeAgo: string;
constructor(question: IQuestion) {
this.timeAgoTicker();
}
timeAgoTicker(): void {
this.timeAgo = 'just now';
setTimeout( () => this.timeAgo = 'about a minute ago', 10000);
setTimeout( () => this.timeAgo = 'a couple of minutes ago', 20000);
setTimeout( () => this.timeAgo = '5 minutes ago', 50000);
// etc...
}
}
我不知道有很多setTimeout調用會對性能產生什么影響,但是我寧願將timeAgo
設置為日期對象,然后在每次更新UI時檢查now
和該日期對象之間的區別:
export interface IQuestion {
createdAt: Date;
}
export class Question implements IQuestion {
public createdAt: Date;
constructor(question: IQuestion) {
this.createdAt = new Date();
}
getAge(): String {
return (new Date() - this.createdAt).toSomeStringAccordingToAge()
}
}
我不知道語法是否正確,因為我不使用Typescript。 例如,如以下提到的評論之一所述,最好使用訪問器( getter
)。
好的, newQuestion
和第一個setTimeout
只是使某些東西可以測試的樣板代碼。 請忽略。 第二個setInteval是我們查看data
屬性的地方。 此屬性符合HTML標准。 可以通過[HTMLElement].dataset
訪問。 我們將發布時間與當前時間進行測試。 用一種方法。
const newQuestion = () => { let target = document.querySelector('.questions'); let question = document.createElement('div'); question.className = 'question'; question.setAttribute('data-question-date', Date.now()); question.innerHTML = '<span>Test Question - <span><span class="age">Just Now</span>'; target.appendChild(question); }; document.addEventListener('DOMContentLoaded', () => { setInterval(() => { newQuestion(); }, 5000); setInterval(() => { let questions = document.querySelectorAll('.question'); questions.forEach(q => { let dateofQ = q.dataset.questionDate; let age = Math.floor((Date.now() - dateofQ)/1000); console.log(`age: ${age}`); let ageElement = q.querySelector('.age'); //do just 20 secs, so we don't have to wait. if(age < 20) { ageElement.innerHTML = 'Just now'; } else if (age < 300) { ageElement.innerHTML = 'Less than 5 minutes ago.'; } else { ageElement.innerHTML = 'More than 5 minutes ago.'; } }); }, 1000); });
<div class="questions"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.