coool
coool

Reputation: 8297

How does yield work as a argument in javascript

I came across this code while learning about yield and wondering what yield would do as a argument to a function . Looks like a glorified return in this place

export function * throttle(func, time) {
  let timerID = null;
  function throttled(arg) {
    clearTimeout(timerID);
    timerID = setTimeout(func.bind(window, arg), time); // what does this do????
  }
  while(true) throttled(yield);
}

export class GeneratorThrottle {

  constuctor() {};

  start = () => {
    thr = throttle(console.log, 3000);
    thr.next('');
  };

  toString = () => {
    console.log(throttle);
    console.log('start =', this.start);
  };
};

Upvotes: 1

Views: 270

Answers (1)

Nur
Nur

Reputation: 2473

With next method, You can pass data as argument into generator function.

function* logGenerator() {
  console.log(0);
  console.log(1, yield);
  console.log(2, yield);
  console.log(3, yield);
}

var gen = logGenerator();

// the first call of next executes from the start of the function
// until the first yield statement
gen.next();             // 0
gen.next('pretzel');    // 1 pretzel
gen.next('california'); // 2 california
gen.next('mayonnaise'); // 3 mayonnaise

And func.bind(window, arg) are just fancy way to call it with argument,

where bind method return a function... And you can access this as window in that function...

Example:

function func(args) {
    console.log(this, args)
}
func.bind("this", "args")();

Upvotes: 1

Related Questions