Javascript

jQuery - $.when() 함수

shb 2022. 3. 16. 16:37

$.when() 함수  
thenable object들 (다른말로 deferred object)의 이벤트가 끝나면 리턴타입은 Promise 객체 리턴
https://api.jquery.com/jquery.when/
  
deferred.then() 함수
deferred 들이 다 마무리 되면 콜백 함수 호출
https://api.jquery.com/deferred.then/

 

$(document).ready(function(){
    $("#run").click(function(e){
         var $box1 = $(".box1");
         var $box2 = $(".box2");
         var $box3 = $(".box3");

     $box1.animate({left : "200px"}, 1000);
     $box2.animate({top: "0px"}, 1500);
//   $box3.animate({top: "150px"}, 1500);

//   alert("언제뜬다?")

  // $box1 과 $box2 의 애니메이션이 다 끝나고 나서 $box3 가 움직이게 하려면?
      // 전제 
  //  : $box1 과 $box2 중 누가 먼저 끝날른지는 모른다
  //  : $box1 과 $box2가 언제 끝날른지는 모른다

// 방법1
// (앞의 작업이 얼마나 걸리는지 안다면?) --> delay()
// $box3.delay(1500).animate({top: "150px"}, 1500);

// 누가 언제 끝날지 알 수 없다.

// 방법2
// $.when() 사용
    $.when($box1, $box2).then(function(){
    $box3.animate({top: "150px"}, 1500);
});

  // $.when() 함수는 
  // thenable object 들 (다른말로 deferred object)들의 이벤트가 끝나면 리턴타입은 Promise 객체 리턴
  // https://api.jquery.com/jquery.when/
  
  // deferred.then() 함수
  // deferred 들이 다 마무리 되면 콜백 함수 호출
  
    });
});

'Javascript' 카테고리의 다른 글

jQuery UI  (0) 2022.03.16
jQuery - AJAX  (0) 2022.03.15
jQuery - filter  (0) 2022.03.15
jQuery - DOM  (0) 2022.03.15
jQuery - Dimension  (0) 2022.03.15