Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why copy function is not working inside setTimeout?

Chrome complains when I try to copy inside setTimeout.

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

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

It doesn't work with the window scope as well.

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

Uncaught TypeError: window.copy is not a function

Interestingly, if I keep the reference to copy and reuse it, it works

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

In Firefox, it doesn't throw any error, but it doesn't work even with the saved reference.

Why copy function doesn't work inside setTimeout, is it a bug?

like image 478
Sanghyun Lee Avatar asked Feb 28 '18 11:02

Sanghyun Lee


People also ask

Does setTimeout block thread?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.

What is alternative to setTimeout?

The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.

Is setTimeout sync or async?

setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.

Is setTimeout guaranteed?

setTimeout is a guarantee to a minimum time of execution.


1 Answers

copy is part of the developer tools' Command Line API and is not available outside the browser console. For example, trying to execute the command in a JavaScript file that's part of a normal web page you'd get the same error.

When you invoke the command inside the setTimeout callback, the execution context is no longer the console so copy doesn't exist anymore.

like image 144
JJJ Avatar answered Sep 26 '22 13:09

JJJ