代码之家  ›  专栏  ›  技术社区  ›  mwilson

我是否以低效的方式使用settimeout?

  •  2
  • mwilson  · 技术社区  · 7 年前

    我有一个角度应用程序,我想实现一个“时间前”功能。如果我提出一些疯狂的“问题”,这是个坏主意吗?

    如果你能想象一个facebook帖子上写着“一分钟前发布的…”,那就是我要拍摄的。

    假设用户从未刷新过页面,并且问题是从标志性中心附加到角度MDOEL的。

    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...
      }
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Zach Smith    7 年前

    我不知道多次settimeout调用的性能影响是什么,但我宁愿设置 timeAgo 作为日期对象,然后检查 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 )

        2
  •  -3
  •   Bibberty    7 年前

    好啊, 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>
    推荐文章