2017-02-24 16 views
1

D3에서 애니메이션을 시작, 중지 및 다시 시작하는 데 하나의 버튼을 사용하고 있습니다.D3, setInterval 및 clearInterval 및 이벤트 처리기가있는 javascript 함수 범위

'animateTheMap'함수 안에 애니메이션을 시작하려면 setInterval에 'animateTimer'를 할당하고 콜백 함수 'stopAnimateTheMap'을 사용하여 애니메이션을 중지 시키려면 동일한 버튼에 click 이벤트를 첨부하십시오.

그러나 stopAnimateTheMap 함수는 'animateTimer'를 볼 수 없습니다. 따라서 "animateTimer"가 정의되어 있지 않습니다.

1) 두 개의 함수를 병합해야합니까, 아니면이를 해결할 수 있습니까? 2) 둘 이상의 '클릭'이벤트를 동일한 버튼에 추가하여 재생하고 애니메이션을 중지이 이벤트를 처리 할 수있는 최적의/적절한 방법인가 나는 처음에 각 이벤트에 대한 각 변수를 생성하고 버튼에 할당했다

감사합니다, 경우 1

var animateMapButton = d3.select('body').append('button').attr({ 
             class: "button", 
             id: "animateMap"}) 
           .text("Animate the map") 

animateMapButton.on("click", animateTheMap) 

function animateTheMap(){ 
            animateMapButton.text("Stop the Animation") 
            animateMapButton.on('click',stopAnimateTheMap) 
            i=0;      

            var animateTimer = setInterval(function(){ 

             if(i<yearArray.length){ 
              i++; 
              d3.select('text.selected').classed('selected',false) 
              d3.select('#year'+yearArray[i]).classed('selected',true) 
              updateMapColor(yearArray[i]) 

              } 
             else{ 
              clearInterval(animateTimer) 
             } 
             },2500) 
          } 


function stopAnimateTheMap(){ 

            clearInterval(animateTimer)  
            animateMapButton.text("Animate the map")           
            animateMapButton.on("click",animateTheMap) 
           } 

답변

1

).?. : 함수 밖에서 animateTimer 변수를 선언하면됩니다.

2) : 애니메이션 처리와 애니메이션 처리간에 토글하는 클릭 핸들러 하나만 사용합니다.

var animateMapButton = d3.select('body').append('button').attr({ 
     class: "button", 
     id: "animateMap"}) 
    .text("Animate the map") 

animateMapButton.on("click", toggleAnimating) 

var animateTimer; 
var isAnimating = false 

function toggleAnimating(){ 
    if (isAnimating) { 
     clearInterval(animateTimer)  
     animateMapButton.text("Animate the map")           
    } 
    else { 
     animateMapButton.text("Stop the Animation") 
     i=0;      

     animateTimer = setInterval(function(){ 

      if(i<yearArray.length){ 
       i++; 
       d3.select('text.selected').classed('selected',false) 
       d3.select('#year'+yearArray[i]).classed('selected',true) 
       updateMapColor(yearArray[i]) 

      } 
      else{ 
       clearInterval(animateTimer) 
      } 
     },2500) 
    } 

    isAnimating = !isAnimating; 
}