2011-02-14 2 views
1

자체 회신 기능을 시작합니다 사용자가 기능 자체를 회신 중지 버튼을 누를 때정지/I이 코드가

function functionName(){ 
    // blablabla 
    // dosomething 
    setTimeout(functionName, 5000); 
} 

그럼 내가 그것을 만들고 싶어를 ... 그래서 코드는

이되고 있음 어떻게
function functionName(){ 
    // blablabla 
    // dosomething 

} 

그가 다시 시작하는 것을 다시 버튼을 누르면 ...

function functionName(){ 
    // blablabla 
    // dosomething 
    setTimeout(functionName, 5000); 
} 

수 있습니다 ID 그거 (jquery로)?

인사말

답변

2

매우 간단하면 JQuery에서 toggle()을 사용하여 두 가지 방법을 전달할 수 있습니다. 하나는 기능을 시작하고 다른 하나는 시간 초과를 중지합니다. 여기

(function toggler() { // don't pollute the global scope 

    var temp; 
    var running = false; 
    var myfunc = function() { 
    do_your_stuff_here(); // a pulsing red box in the Fiddle example 
    running = true; 
    temp = setTimeout(myfunc, 1000); 
    } 

    $('#toggle').click(function(e) { // toggler control is a link 
    e.preventDefault(); 
    if (running) { 
     clearTimeout(temp); // turn it off 
     running = false; 
    } else { 
     myfunc(); // or turn it on 
    } 
    }); 

    myfunc(); // kickstart it 

})(); 

이 작업 바이올린의 :

var timeoutId; 

function functionName(){ 
    // blablabla 
    // dosomething 

    timeoutId = setTimeout(functionName, 2000); 
} 


$(document).ready(function(){ 
    $('#myButton').toggle(function() { 
     functionName(); 
    }, function() { 
     clearTimeout(timeoutId); 
    }); 
}); 
0

clearTimeout를 사용할 수있는 타이머를 중지하십시오.

var timerId = setTimeout(functionName, 5000); 

clearTimeout(timerId); 

로직을 실행하려면 어떤 버튼을 클릭했는지 확인할 수 있습니다.

나는 당신이 찾고 있던 것에 대해 100 % 명확하지 않았기 때문에 적어도 타이머를 멈추는 방법에 대한 질문에 대답 할 것입니다.

+0

하지만 난에 사항 clearTimeout을 사용하는 방법을 내 현재 스크립트? – Thew

3

setTimeout은 access-id를 반환합니다. 이 id는 clearTimeout()을 호출하여 현재 시간 초과를 중지하고 "기능 루프"를 종료하는 데 사용될 수 있습니다.

function functionName() { 
    if(this.tID) { 
     clearInterval(tID); 
     delete this.tID; 
    } 

    // do something 

    this.tID = setTimeout(functionName, 5000); 
} 

this은 그렇게라는 window 객체를 참조합니다. 아마도 id를 저장하기 위해 네임 스페이스를 사용하는 것이 더 좋은 생각 일 것입니다.