2014-05-09 2 views
0

이 기능 중 하나만 실행하면됩니다. 다른 함수를 계속 실행하면서 함수 실행을 중단 할 수 있습니까?하나의 기능을 다른 모든 기능을 중지시키는 방법이 있습니까?

예를 들어 "do_move_right()"함수가 현재 실행중인 경우 함수를 실행 중지시키는 버튼을 눌러 "do_move_left()"함수를 시작하려고합니다.

CODE :

function do_move_right() { 
    sheepr = document.getElementById('sb'); 
    mover = sheepr.style.left; 
    mover = parseInt(mover.substring(0,mover.length-2)); 


    mover += 10; 
    sheepr.style.left = (mover)+'px'; 


    if (mover < 940) { 

     window.setTimeout(function() { 
     do_move_right('sb'); 
     }, 250); 
    } 
} 

function do_move_left() { 
    sheepl = document.getElementById('sb'); 
    movel = sheepl.style.left; 
    movel = parseInt(movel.substring(0,movel.length-2)); 


    movel -= 10; 
    sheepl.style.left = (movel)+'px'; 


    if (movel < 940) { 

     window.setTimeout(function() { 
     do_move_left('sb'); 
     }, 250); 
    } 
} 

function do_move_up() { 
    sheepu = document.getElementById('sb'); 
    moveu = sheepu.style.top; 
    moveu = parseInt(moveu.substring(0,moveu.length-2)); 


    moveu -= 10; 
    sheepu.style.top = (moveu)+'px'; 


    if (moveu < 940) { 

     window.setTimeout(function() { 
     do_move_up('sb'); 
     }, 250); 
    } 
} 

function do_move_down() { 
    sheepd = document.getElementById('sb'); 
    moved = sheepd.style.top; 
    moved = parseInt(moved.substring(0,moved.length-2)); 


    moved += 10; 
    sheepd.style.top = (moved)+'px'; 


    if (moved < 940) { 

     window.setTimeout(function() { 
     do_move_down('sb'); 
     }, 250); 
    } 
} 

답변

2

자바 스크립트가 동시에 두 가지 기능을 실행 할 수 없습니다. 함수가 입력되면 함수가 반환 될 때까지 함수가 계속됩니다. 함수 자체가 일찍 리턴하지 않으면 인터럽트 할 수 없습니다 (예를 들어, if 문을 사용하여 종료 조기 종료를 확인하는 경우).

그래서 당신이 찾고있는 뭔가가 바로 기능을 확인하기 위해 자신의 일을 할 수 있는지 확인하는 즉시 설정할 수있는 변수입니다. 같은 뭔가 : 당신은 아무것도를하고 테스트가 실패 할 경우 조기 반환하기 전에

var canMoveLeft = true; 

은 그냥 do_move_left() 함수에서 해당 VAR을 확인합니다.

+0

실제로 내부 함수 내용을 if 문으로 래핑하여 테스트가 통과하든 실패하든 if 문 닫는 중괄호 바로 뒤에 setTimeout을 수행 할 수 있습니다. –

관련 문제