2016-12-02 2 views
0

반복 작업에 setInterval 함수를 사용하고 싶습니다. 한 번 작동하는 자동 업데이트 기능이 있습니다.setInterval 함수는 한 번만 작동합니다.

var intervalId; 

function autoUpdate() { 
    intervalId = setInterval(updateFile(fileId, 'root', document.getElementById('editor').value), 10000); 
} 

여기에 내 stopAutoUpdate 기능이 있습니다.

function stopAutoUpdate() { 
    clearInterval(intervalId); 
} 

이 코드의 잘못된 점은 무엇입니까? 고맙습니다.

편집 = 제목을 편집했습니다. 죄송합니다.

+0

은 - 당신이 한 번만 실행되는 것을 의미합니까? 그래서 그것은 작동하지 않는'setInterval'입니까? 'clearInterval' 아닌가요? – Quentin

+0

제목은 빨간색 청어이며 복제본은 정확합니다. – zzzzBov

+0

@Atti 기능을 실행하지 마십시오 - 여기를 참고하십시오 -> https://jsfiddle.net/myt05mad/ – hack3rfx

답변

3

당신은 제대로 간격 기능을 설정해야합니다 :

function autoUpdate() { 
    intervalId = setInterval(function(){ 
     updateFile(fileId, 'root', document.getElementById('editor').value) 
    }, 10000); 
} 

당신이 실제로 통과 한 x 함수를 호출하고 있습니다. clearInterval 자체가 올바르게 보입니다.

+0

@Lain이 무엇을 말하고 있는지 명확히하기 위해 각 간격에서 실행해야하는 것으로 설정하는 대신 updateFile 함수를 호출하는 것입니다. 편집 : 그는 나중에 자신을 지워서 나를 무시하므로 :) – Pabs123

+0

@Lain Man은 중립적이지 않습니다. –

+0

@Mike C : 역사적으로 볼 때, 그것은 존재할 수도 있고있을 수도 있습니다. 한 남자가 예전에 '인류'같은 표현으로 볼 수있는 사람이었습니다. – Lain

0

문제는이 function definition를 수신하지만이 clearInterval 문제 어디에도없는 function execution

0

의 결과를 제공, 사용자가 설정 setInterval PARAM 함께. setInterval을 잘못 사용하고 있으며 범위에 ID가 없을 수도 있습니다. 작동 원리에 대한 간단한 예제가 있습니다. "한 시간을 작동"

// Make sure the ID is declared somewhere that both functions 
 
// can access it 
 
var intervalID; 
 
var calls = 0; 
 

 
function displayStuff(a, b, c) { 
 
    console.log(a, b, c); 
 
    calls++; 
 
    
 
    if (calls >= 10) { 
 
    stopAutoUpdate(); 
 
    } 
 
} 
 

 
function autoUpdate() { 
 
    intervalID = setInterval(function() { 
 
    // Notice how I'm wrapping the call in an anonymous function 
 
    // without this, it will just call the function once, not repeat it 
 
    displayStuff('Auto:', intervalID, calls); 
 
    }, 800); 
 
} 
 

 
function stopAutoUpdate() { 
 
    clearInterval(intervalID); 
 
    console.log('Done'); 
 
} 
 

 
// Start the interval 
 
autoUpdate();

관련 문제