toggle-toggle / javascript-basic

🌱우아한 테크코스 프론트엔드 자바스크립트 기초 스터디 입니다.
9 stars 0 forks source link

[Event Loop] 다음 문제에 대해서 Event Loop의 Call Stack과 연관지어 설명해주세요. #34

Open devhyun637 opened 3 years ago

devhyun637 commented 3 years ago

버튼을 선택하면 div가 500만틈 움직였다가 300만큼 돌아오는 코드를 짜보았는데, 제대로 동작하지 않습니다. 그 이유를 Event Loop의 Call Stack과 관련지어 설명해주세요.

<!doctype html>
<html class="no-js" lang="">

<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    .box {
      margin: 10px;
      width: 50px;
      height: 50px;
      background-color: red;
    }
  </style>
</head>

<body>
  <button id="button1">Let's go</button>
  <div class="box"></div>
<script>
  const button1 = document.querySelector('#button1');
  const box = document.querySelector('.box');

  button1.addEventListener('click', () => {
    box.style.transition = 'transform 1s ease-in';
    box.style.transform = 'translateX(500px)';
    box.style.transform = 'translate(300px)';
  })
</script>
</body>

</html>
shinsehantan commented 3 years ago

버튼 클릭 시 콜백 함수를 호출하게 되고, 콜스택에 들어가면 이벤트 루프가 돌다가 3개 코드를 모두 태스크 큐에 가져가서 실행하게 되는데, 따로 실행하는 것이 아니라 3줄의 코드가 모두 실행된 후에 렌더가 이루어지기 때문에 마지막에 실행된 코드의 결과만 보여집니다.