Beginner
Beginner

Reputation: 9095

ES6 - generators using for count

I was trying to create a counter using generators where user will click on the button and the count value will be increased. When i tried to get the function i am not getting that one. Am i missing something .

Thanks in Advance

index.html

  <div class="counter">
     <div id="count-gen">0</div>
     <button onclick="countGen()">Count</button>
    </div>

index.js

 function* countGen(){
    let count =0;
    let nextValue = yield count++
    document.getElementById('count-gen').innerHTML = nextValue
  }

Upvotes: 2

Views: 766

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

You've conflated two things which should be separate: Your generator, and the event handler for using your generator. You also need to be using the generator's iterator:

The generator (note the loop):

function* countGen() {
  let count = 0;
  while (true) {
    yield ++count;
  }
}

(I also made it a pre-increment as you appeared to want to start at 1.)

Getting the iterator:

const count = countGen();

Using the iterator:

function handler() {
  document.getElementById('count-gen').innerHTML = count.next().value;
}

Live Example:

function* countGen() {
  let count = 0;
  while (true) {
    yield ++count;
  }
}

const count = countGen();

function handler() {
  document.getElementById('count-gen').innerHTML = count.next().value;
}

document.querySelector("button").addEventListener("click", handler);
<div class="counter">
  <div id="count-gen">0</div>
  <button>Count</button>
</div>

(The example also uses addEventListener rathern than an onxyz-attribute handler.)

Upvotes: 4

Related Questions