Self-Invoke JavaScript函数是否会导致堆栈溢出异常

时间:2018-06-10 19:50:53

标签: javascript function settimeout stack-overflow

这里我有一个在setTimeout回调函数中调用自身的函数:

function myFunc(){

    // ... I'm doing my jobs here...

    setTimeout(function(){
        myFunc() //self invoke
    },1)
}

myFunc(); // start point

这段代码最终会发生堆栈溢出异常吗? 提前谢谢。

1 个答案:

答案 0 :(得分:3)

没有。通过@Data @NoArgsConstructor @AllArgsConstructor @Entity public class Book { @Id @SequenceGenerator(name = "book_id_seq_gen", sequenceName = "book_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_id_seq_gen") private long id; private String name; private int year; @ManyToOne private Writer writer; private String description; private int downloadNumber; @ManyToMany @JoinTable(name = "book_genre", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "genre_id") ) private Set<Genre> genres; } @Data @NoArgsConstructor @AllArgsConstructor @Entity public class Writer { @Id @SequenceGenerator(name = "writer_id_seq_gen", sequenceName = "writer_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "writer_id_seq_gen") private long id; @NotNull(message = "Name cannot be null") @Length(min = 1, max = 100) private String name; @NotNull(message = "Surname cannot be null") @Length(min = 1, max = 100) private String surname; private String description; @OneToMany(mappedBy = "writer") private List<Book> books; } 排队的函数仅在主线程(或当前正在进行的任何线程)完成后运行 - 没有嵌套调用/嵌套环境可能导致您担心的溢出。如果您运行此代码段,则永远不会遇到错误,例如:

&#13;
&#13;
setTimeout
&#13;
&#13;
&#13;

同样的事情适用于调用通过function myFunc(i) { if (i % 1000 === 0) console.log(i); setTimeout(function() { myFunc(++i) }) } myFunc(0);递归调用自己的promises的函数 - 它非常安全。