Javascript/GMA(2302~)

23.04.26 자바스크립트 제너레이터 함수 예제

hyerin1201 2023. 4. 27. 00:16

 

<body>
  <h1>경강선 노선</h1>
  <button>다음역</button>
  <span id="result">출발</span>
</body>
body {
  display: flex;
  flex-direction: column;
  align-items: center;
}
button {
  width: 150px;
  padding: 10px 20px;
}
button:hover {
  cursor: pointer;
}
#result {
  border: 1px solid #ccc;
  text-align: center;
  padding: 20px;
  font-weight: bold;
  margin-top: 10px;
}
//제너레이터 함수 예제
function* train() {
  yield "판교";
  yield "이매";
  yield "삼동";
  yield "경기광주";
  yield "초월";
  yield "곤지암";
  yield "신둔도예촌";
  yield "이천";
  yield "부발";
  yield "세종대왕릉";
  yield "여주";
}

let gyeonggang = train();

const button = document.querySelector("button");
const result = document.querySelector("#result");

button.addEventListener("click", () => {
  let current = gyeonggang.next();
  if(current.done !== true) {
    result.innerText = current.value;
  } else {
    result.innerText = "종점";
    button.setAttribute("disabled", "disabled");
  }
})