2014-10-07 4 views
1
var intervalHandle ; 
var currentOpacity=0; 

function beginAnimate() { 
    current_question_div = document.getElementById(current_question); 
    intervalHandle = setInterval(function(){ 
     animateBox(current_question_div) 
    }, 200); 
    alert("Hellow ashik !"); 
} 

function animateBox(current_question_div) { 
    current_question_div.style.backgroundColor = "lightblue"; 
    currentOpacity = currentOpacity + .091; 
    current_question_div.style.opacity = currentOpacity; 
    if(currentOpacity > 1) {  
     alert("END"); 
     clearInterval(intervalHandle); 
    } 
} 
<P onclick="beginAnimate">Click</p> 

모든 것이 괜찮 자바 스크립트 setInterval을 기능을 실행하지만, alert("Hellow ashik !");. clearInterval이 발생했을 때 alert("Hellow ashik !")을 열려고합니다. 이제는 다른 JavaScript 코드도 간격이 실행되는 동안 병렬로 실행됩니다. 한 번에 하나의 스레드 만 실행해야합니다. 도와주세요. 이 코드를 하나씩 실행하는 방법이 있습니까? 감사.만 간격이 실행되는 동안 작업

+0

다른 스레드가 없으므로 JS가 병렬로 실행되지 않습니다. 간격은 * 비동기 적으로 * 실행됩니다. – Bergi

+0

코드가 "하나씩"실행 중입니다. * setInterval *을 호출하면, 전달 된 함수는 최소한 200ms 동안 호출되지 않지만 코드의 다음 행 ('alert ('...')')은 즉시 호출됩니다. 하나의 스레드 만 작동합니다. 자바 스크립트는 단일 스레드이므로, * beginInitval *에 전달 된 함수는 * beginAnimate *가 완료 될 때까지 실행할 수 없습니다 (간격을 0으로 설정하더라도). – RobG

답변

0

이 코드 당신이 원하는 것을 달성해야

var intervalHandle, 
    currentOpacity = 0; 

function beginAnimate() 
{ 
    current_question_div=document.getElementById(current_question); 

    /* call any other functions that need to run before the animation starts here */ 
    alert("Hellow ashik !"); 

    intervalHandle = setInterval(function(){ 
     // note 'endAnimate()' is passed to the 'animateBox()' function as a callback 
     animateBox(current_question_div, endAnimate) 
    }, 200); 

    /* call any functions that can run while the animation is running here */ 
} 

function endAnimate() { 
    alert("The end!"); 
    /* call any other functions that need to be run after the animation here */ 
} 

function animateBox(current_question_div, callback) { 
    current_question_div.style.backgroundColor = "lightblue"; 
    currentOpacity = currentOpacity + .091; 
    current_question_div.style.opacity = currentOpacity; 

    if(currentOpacity>1) 
    {  
     alert("END"); 
     clearInterval(intervalHandle); 
     if (callback && typeof(callback) === 'function') { 
      callback(); 
     } 
    } 
} 

<P onclick="beginAnimate">Click</p> 

자바 스크립트는 단일 스레드 언어 - WebWorkers 또는 다른 해결 방법을 무시. 그러나 비동기식이므로 스레딩과 같은 동작을 자주 볼 수 있습니다. 이러한 문제를 해결하는 한 가지 방법은 callback pattern을 사용하는 것입니다.

콜백 패턴에서 비동기 함수가 완료 될 때 나중에 호출 할 함수를 전달합니다. 자바 스크립트는 함수가 퍼스트 클래스 객체이기 때문에 이것을 간단하게 만들고 번호처럼 쉽게 전달하거나 할당 할 수 있습니다.

+0

감사합니다. 그러나 실제로 저는 처음부터 경고를 실행하고 싶습니다. 나는 경고 만 언급한다. 하지만 너무 많은 작업이있을 수 있습니다. alert ("Hellow ashik!") 후에 애니메이션이 시작됩니다. –

+0

물론, 실제로 코드를 변경하지는 않습니다. 옵저버 또는 다른 비동기 패턴 중 하나를 사용해야합니다. – klyd

+0

그리고 만약 내가 초심자에게 경고를 걸면 그것은 간격이 끝나기 전에 실행 중입니다. 감사. @klyd –

0

브라우저에서 javaScript는 단일 스레드 특성을 가지므로 브라우저 당 하나의 스레드에서 실행됩니다. 이는 실행 다이어그램이 1 차원임을 의미합니다. javaScript는 한 번에 하나의 코드 만 실행할 수 있습니다.

브라우저는 이벤트 기반입니다. 대부분의 이벤트는 마우스 클릭, 키 누름 및 timers과 같은 비동기식입니다. 이들은 실행이 시작될 때만 실행됩니다. 그 동안 그들은 실행을 기다리는 이벤트 대기열에 들어가야합니다.

<p id="test"></p> 

document.getElementById("test").innerHTML += "a"; 

var intervalHandle = setInterval(function(){ 
    callback(); 
}, 200); 

document.getElementById("test").innerHTML += "c"; 

function callback() { 
    document.getElementById("test").innerHTML += "b"; 
    //here where should be located all the code supposed to be executed after the timeinterval. 
    clearInterval(intervalHandle); 
    //here where should be located all the code supposed to be executed after the clearInterval. 
} 

작업 예제를 보려면이 링크 jsfiddle을 확인하십시오.

위 예제에서 javascript 스레드는 p의 내용을 "a"로 설정하기 시작하고 콜백 실행을 지연합니다. 200ms 후에 가장 가까운 타이머 틱의 이벤트 대기열로 이동합니다. 그리고 p의 내용을 "c"로 설정하여 실행을 계속합니다.

그래서 clearInterval 다음에 무언가를 실행하려면 clearInterval 뒤에 배치해야합니다.

희망이 있습니다. 유용합니다.

관련 문제