[Javascript] Broadcaster + Operator + Listener pattern -- 7. Create a broadcaster forOf

The patterns we've established can also work well with plain old Objects and Arrays. We just have to capture the behavior of accessing those values inside of our broadcaster so the values can be passed down into a listener.

We will create a custom forOf function to implement an scenario where we can type out a letter every second, this is basically grouping the behavior of some of our broadcasters.

We will call our forOf function a broadcaster creator. This function will take two arguments, an Iterable and a listener and, as our current pattern, we will use curry to handle the arguments. Our forOf will just iterate over the iterable argument and will call the listener in each iteration.

let forOf = curry((iterable, listener) => {
  for (let i of iterable) {
    listener(i)
  }
})

The question is how to implement the cancel behavor?

We can wrap with setTimeout:

let forOf = curry((iterable, listener) => {
  let id = setTimeout(() => {
    for (let i of iterable) {
      listener(i)
    }
  }, 0)
  return () => {
    clearTimeout(id)
  }
})
原文地址:https://www.cnblogs.com/Answer1215/p/13869738.html