不带回调函数的 SetTimeout() 调用行为异常

SetTimeout() call without callback function behaves in unexpected manner

我刚刚尝试使用 settimeout() 函数,并在一次尝试中写下了以下代码:

console.log(setTimeout('a', 1000));

当我执行此语句时,我在控制台上收到以下输出:

我明白错误 a is undefined 出现是因为 setTimeout() 需要一个函数作为它的第一个参数,但为什么我看到数字 379, 380 在控制台上。我相信这是自 setTimeout() 命令在当前会话中首次执行以来经过的秒数。 我对此是否正确?有人可以更详细地解释一下吗?

您看到的数字是由 setTimeout 函数返回的 timeoutID。 通过将 ID 传递给 clearTimeout.

,ID 可用于取消超时

详细了解 setTimeout here and clearTimeout here

您在控制台中看到的数字是 setTimeout() 调用返回的 ID,稍后您可以使用它来清除超时即取消它。

例如:

const id = setTimeout(console.log, 1000, "this is cancelled");
clearTimeout(id); //cancelling the earlier timeout
setTimeout(console.log, 1000, "this is not cancelled");

来自 MDN docs:

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

还有一种 setTimeout() 的变体,它的作用类似于 eval() 函数,不推荐使用,大多数安全扫描工具都会对其进行标记,该工具采用字符串表达式并将表达式计算为 JavaScript 代码并在计时器到期后立即执行,例如:

const id = setTimeout("console.log('cancelled')", 1000);
clearTimeout(id);
setTimeout("console.log('not cancelled')", 1000);

在您的代码中,您在传递 'a' 时使用了此变体,您收到错误是因为当解释器评估您的字符串时,它无法在当前范围内找到变量 a

const a = 'This is a';
setTimeout('console.log(a)', 1000);