// 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());
어떤 프로세스 ID? 별도의 프로세스가 없습니다. – akonsu
setTimeout이 스레드를 생성합니까? – lelloman
그 코드는있는 그대로 작동합니다. 물론 @ 아니다. JS에는 스레드가 없습니다. –