这段代码会导致堆栈溢出吗?Javascript setTimeout() [英] Will this code cause a stack overflow? Javascript setTimeout()

查看:32
本文介绍了这段代码会导致堆栈溢出吗?Javascript setTimeout()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我想知道这是否会导致堆栈溢出.我不熟悉 setTimeout 函数的处理方式及其后果.

I have the following code, and I was wondering if this will cause a stack overflow. I am not familiar with the way the setTimeout function is handled and its consequences.

function func1() {
    // some logic for the dynamicTimeout
    setTimeout("func2()", dynamicTimeout);
}

function func2() {
    // do something
    func1();
}

推荐答案

setTimeout 调度一个函数在延迟后执行,并且scheduler"函数的堆栈没有保留,所以一个堆栈由于setTimeout,不会直接发生溢出.

setTimeout schedules a function to be executed after a delay, and the "scheduler" function's stack isn't preserved, so a stack overflow will not occur directly due to the setTimeout.

一般来说,许多浏览器对以这种方式调度的函数强制执行最小超时(因此,即使您将 0 作为超时传递,或者根本不传递,该函数也不会立即安排).即使不是这种情况,该函数也会被添加到等待操作的队列中,如果执行其他操作,则会被延迟.

In general, many browsers enforce a minimum timeout for functions scheduled this way (so even if you pass 0 as the timeout, or don't pass one at all, the function won't be scheduled immediately). Even if this isn't the case, the function gets added to a queue of waiting operations, and will be delayed if something else if executing.

附带说明,无需将字符串传递给 setTimeout.它得到 eval 'd,这有时是不安全的并且通常很慢.最好只传递一个函数引用:setTimeout(func2, dynamicTimeout).

As a side note, there's no need to pass a string to setTimeout. It gets eval'd, which is sometimes insecure and generally slow. Better to just pass a function reference: setTimeout(func2, dynamicTimeout).

这篇关于这段代码会导致堆栈溢出吗?Javascript setTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆