2013-06-24 2 views
3

Java 스레드가 자체 스레드 ID에 액세스 할 수 있으므로 setTimeout/setInterval 호출의 프로세스 ID에 이벤트 함수 내에서 액세스하려면 어떻게해야합니까?JavaScript에서는 setTimeout/setInterval 호출의 id에 이벤트 함수 내부에서 어떻게 액세스합니까?

var id = setTimeout(function(){ 
    console.log(id); //Here 
}, 1000); 
console.log(id); 
+1

어떤 프로세스 ID? 별도의 프로세스가 없습니다. – akonsu

+0

setTimeout이 스레드를 생성합니까? – lelloman

+2

그 코드는있는 그대로 작동합니다. 물론 @ 아니다. JS에는 스레드가 없습니다. –

답변

4

그 코드가 작동 할 것이다 것과 같이, 당신은, 제로, 또는 음의 매우 작은 시간 제한 값을 전달하는 경우에도, 제공된 콜백을 호출하기 전에 setTimeout 것이다 항상 수익입니다.

> var id = setTimeout(function(){ 
     console.log(id); 
    }, 1); 
    undefined 
    162 
> var id = setTimeout(function(){ 
     console.log(id); 
    }, 0); 
    undefined 
    163 
> var id = setTimeout(function(){ 
     console.log(id); 
    }, -100); 
    undefined 
    485 

문제는 많은 동시에 예정 익명의 활동을 할 계획이다, 그래서 그들은 같은 변수에서 자신의 ID를로드 할 수 없습니다.

물론 가능합니다.

(function() { 
    var id = setTimeout(function(){ 
    console.log(id); 
    }, 100); 
})(); 
+0

문제점 많은 익명 작업이 동시에 예정되어 있습니다. 동일한 변수에서 ID를로드 할 수 없습니다. – user1636586

+1

@ user1636586 ID를 어레이로 밀어 넣고 배열을 반복하여 지우십시오. – Racheet

+0

@ user1636586 내 수정을 참조하십시오. –

1

setTimeout에 전달 된 함수는 어떤 식 으로든 사실을 인식하지 못합니다. 프로세스 ID 나 스레드 ID가 아니라 이상한 API 결정입니다.

+1

그것은 이상한 API 결정이 아닙니다. 나중에 타임 아웃을 취소하기위한 핸들입니다. –

+3

네,'var l = 100000;을 사용하여 모든 타임 아웃을 취소 할 수있는 이상한 API는 아닙니다. while (l--) clearTimeout (l)'. 가장 무거운 래퍼라도 수정할 수는 없습니다. – Esailija

0
// Creates timeout or interval based on parameters: 
// timeoutOrInterval: string, 'timeout' or 'interval' 
// worker: function, worker with signature function(procRef) 
// timeout: int, timeout in ms 
// context: optional, window object (default is 'window'), can be a window of an iframe, for istance 
// see usage below 
function makeTimeoutOrInterval(timeoutOrInterval, worker, timeout, context){ 
    var isTimeout = (timeoutOrInterval == 'timeout'), method = isTimeout ? 'setTimeout': 'setInterval',id, result = getObjectFor(id = (context || window)[method](function(){ 
    worker.call(this, (result = getObjectFor(id, isTimeout))); 
    }, timeout), isTimeout); 
    return result; 
    function getObjectFor(id, isTimeout) { 
    return { 
     getId: function() { return id; }, 
     cancel: function() { 
      if (id) { 
      if (isTimeout) 
       window.clearTimeout(id); 
      else 
       window.clearInterval(id); 
      id = null; 
      } 
     } 
    }; 
    } 
} 

// Usage: 
var counter = 0; 
var procRefOuter = makeTimeoutOrInterval('interval', function(procRef){ 
    // procRef - object with two methods: getId() and cancel() - to get and id of a worker process or cancel execution 
    console.log(procRef.getId()); 
    console.log ('Counter: ' + (counter++)); 
    if (counter == 10) { 
     procRef.cancel(); // we can cancel further execution inside the worker 
    } 
}, 2000); 

procRefOuter is exactly the same as procRef explained earlier. Only outside. 

console.log(procRefOuter.getId()); 
+0

이 답변은 무엇입니까? –

관련 문제