In my code I am trying to do a javascript exercise. On the second line, I’m trying to get the ogTimeout to store a reference to setTimeout function since I will reassign a new definition to setTimeout.
However I get the error “ReferenceError: Cannot access ‘setTimeout’ before initialization”. I understand that it’s saying that setTimeout should be initialized, but it already is a existing function, so I don’t understand what’s causing the error.
Any help appreciated, thank you!
const timeouts = [];
const ogTimeout = setTimeout;
let setTimeout = function(method, timeInMs) {
const timeoutRef = ogTimeout(method, timeInMs);
timeouts.push(timeoutRef);
}
const clearAllTimeouts = function() {
while (timeouts.length) {
const timeoutRef = timeouts.pop();
clearTimeout(timeoutRef);
}
}
setTimeout(() => console.log("Callback after 5 seconds."), 5000);
Tried searching referenceerror and its details.
it’s saying that setTimeout should be initialized, but it already is a existing function
No, it’s the let setTimeout
that you declared yourself, which is not yet initialised when const ogTimeout = setTimeout
runs. Accessing it during the temporal dead zone causes this error.
I will reassign a new definition to setTimeout.
To overwrite the global setTimeout
, don’t declare your own variable. Remove the let
and write only
setTimeout = function(method, timeInMs) {
const timeoutRef = ogTimeout(method, timeInMs);
timeouts.push(timeoutRef);
};
Or to be even more explicit, you can also assign to the property of the global window
object:
window.setTimeout = function(method, timeInMs) {
const timeoutRef = ogTimeout(method, timeInMs);
timeouts.push(timeoutRef);
};
Btw for this to not break any code, do not forget to also return timeoutRef
from your function.
try
const ogTimeout = globalThis.setTimeout;
Thank you that works! Thank you so much. @JaromandaX
@Ima this is due to whats called hoisting, see developer.mozilla.org/en-US/docs/Glossary/Hoisting
@ug_ variables declared using let/const are not hoisted
@JaromandaX Sure they are, see stackoverflow.com/q/31219420/1048572
Show 2 more comments