See a JavaScript pen test online, the feeling is very interesting, in this record.

Check out closures, event polling, chain calls, queues

Implementing a LazyMan can be called as follows: LazyMan(" Hank ") output: Hi! This is Hank! LazyMan (" Hank "). Sleep (10) eat (" dinner ") output Hi! This is Hank! // Wait 10 seconds.. Wake up after 10 Eat dinner~ LazyMan(" Hank ").eat(" dinner ").eat(" supper ") output Hi This is Hank! Eat supper~ Eat supper~ LazyMan(" Hank ").sleepfirst (5).eat(" supper ") output // Wait 5 seconds Wake up after 5 Hi This is Hank! Eat supper and so on.Copy the code

Here’s how ES6 works. If you’re writing in ES5, you’ll need to write more code to maintain this.

class _LazyMan {
  constructor(name) {
    this.tasks = [];
    const task = () => {
      console.log(`Hi! This is ${name}`);
      this.next();
    }
    this.tasks.push(task);
    setTimeout() => {// Put this.next() on the call stack to clear this.next(); }, 0); }next() { const task = this.tasks.shift(); // Take the first task and execute task && task(); } sleep(time) { this._sleepWrapper(time,false);
    returnthis; } sleepFirst(time) {this._sleepwrapper (time,true);
    return this;
  }

  _sleepWrapper(time, first) {
    const task = () => {
      setTimeout(() => {
        console.log(`Wake up after ${time}`);
        this.next();
      }, time * 1000)
    }
    if(first) { this.tasks.unshift(task); // put it at the top of the queue}else{ this.tasks.push(task); }} eat(name) {const task = () => {console.log(' eat${name}`);
      this.next();
    }
    this.tasks.push(task);
    returnthis; }}function LazyMan(name) {
  return new _LazyMan(name);
}
Copy the code

I want to change my job recently, and I have been preparing for the interview. When REVIEWING, I feel that there are many knowledge points that can be tested in the front end.

Reference: https://zhuanlan.zhihu.com/p/22387417