Why does copy function not work inside setTimeout?

Chrome complains when I try copyinside setTimeout.

setTimeout(function () { copy('a') }, 0)

Uncaught ReferenceError: copy is not defined
    at <anonymous>:1:26

It also does not work with the area window.

setTimeout(function () { window.copy('a') }, 0)

Uncaught TypeError: window.copy is not a function

Interestingly, if I keep the link to copyand reuse it, it works

cc = copy;
setTimeout(function () { cc('a') }, 0);

In Firefox, it does not cause any errors, but it does not work even with a saved link.

Why the function copydoes not work inside setTimeout, is this an error?

+6
source share
3 answers

copy API . , JavaScript - .

setTimeout, , copy .

+4

with , , , copy() setTimeout() , , :

with ({ copy }) { setTimeout(() => copy("copied!"), 0) }

copied! . , Firefox.

+2

The above workarounds are good, but I found the easiest workaround is to simply assign var copy2 = copy;and use it instead copy2, since the handler setTimeouthas access to global variables.

var copy2 = copy;
setTimeout(() => copy2('hi'), 500);
0
source

Source: https://habr.com/ru/post/1694234/


All Articles