如何从事件函数内部访问 setTimeout/setInterval 调用的进程 ID,因为 Java 线程可能会访问其自己的线程 ID?
var id = setTimeout(function(){
console.log(id); //Here
}, 1000);
console.log(id);
如何从事件函数内部访问 setTimeout/setInterval 调用的进程 ID,因为 Java 线程可能会访问其自己的线程 ID?
var id = setTimeout(function(){
console.log(id); //Here
}, 1000);
console.log(id);
该代码将按原样工作,因为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);
})();
传递给的函数以setTimeout
任何方式都不知道这一事实。这不是进程 ID 或线程 ID,只是一个奇怪的 API 决定。
// 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());