An interesting article about timers in JS: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
setImmediate(...)
is Microsoft nonsense.
https://developer.mozilla.org/en-US/docs/Web/API/Window/setImmediate
Passing arguments:
// We can use: setTimeout(func, delay, arg1, arg2, arg3, ...)
I suggest avoid doing that. First, it is not clear if it works in most of the browsers: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Browser_compatibility
Secondly it is a specific way to pass parameters that works for setTimeout
, and not for other functions (like array.forEach).
The general method is to use .bind(...)
(almost obsolete now) or a (arrow) function:
// solution1.js with arrow funtionsconst theOneFunc = delay => {
console.log('Hello after ' + delay + ' seconds');
};setTimeout(() => theOneFunc(4), 4 * 1000);
setTimeout(() => theOneFunc(8), 8 * 1000);
Finally, the this
problem is more related to the way a function is called rather than to the caller.
const obj = {
id: '42',
whoCalledMe() {
console.log('Caller is', this);
}
};obj.whoCalledMe(); // Logs Caller is {id: "42", whoCalledMe: ƒ}
const method = obj.whoCalledMe;
method(); // Logs Caller is Window {...}
In the example
setTimeout(obj.whoCalledMe, 0);
you pass the function whoCalledMe
to setTimeout
, not the method of the object obj
. That’s why you loose the this
context, which originally was obj
.