How can I access the process id of setTimeout/setInterval call from inside its event function, as a Java thread might access its own thread id?
var id = setTimeout(function(){
console.log(id); //Here
}, 1000);
console.log(id);
That code will work as-is, since setTimeout will always return before invoking the provided callback, even if you pass a timeout value which is very small, zero, or negative.
> 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
Problem is I plan to have many concurrently scheduled anonymous actions, so they can't load their id from the same variable.
Sure they can.
(function () {
var id = setTimeout(function(){
console.log(id);
}, 100);
})();
The function passed to setTimeout is not aware of the fact in any way. And that's not a process id or thread id, just a weird API decision.
// 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());
来源:https://stackoverflow.com/questions/17280375/in-javascript-how-can-i-access-the-id-of-settimeout-setinterval-call-from-insid