javascript中的递归setTimeout [英] Recursive setTimeout in javascript

查看:83
本文介绍了javascript中的递归setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以无限期运行此操作,而不会导致堆栈溢出或内存不足?

Is it possible to run this "indefinitely", without causing stack overflow or running out of memory?

function eternal(){
    var time = recalculateTime();
    doSomething();
    setTimeout(eternal,time);
}

setTimeout(eternal,200000);

我没有使用setInterval,因为触发时间是可变的。

I'm not using setInterval, because the triggering time is variable.

推荐答案

这实际上不是一个递归调用,因为 eternal()的第一次调用实际上已经完成了 setTimeout()调用下一个。因此,它不是技术上的递归,也不会随着时间的推移而构建堆栈。它可以永久运行而不会产生任何累积,这是一种非常好的方法来保持一遍又一遍地运行。

This is not actually a recursive call because the first invocation of eternal() has actually finished before the setTimeout() calls the next one. So, it's not technically recursion and does not build up the stack over time. It can run forever without any buildup and this is a perfectly fine way to keep something running over and over.

为了回应你的一条评论,javascript不是多重的线程,因此它不会为计时器创建多个线程。每个触发的计时器事件只是将一个事件放入事件队列中,如果当时没有JS正在运行,则触发该事件(从而调用回调函数)。如果JS当时正在运行,JS引擎会等待,直到当前正在执行的JS完成,然后为事件队列中的下一个事件提供服务(从而调用回调)。

In response to one of your comments, javascript is not multi-threaded so it does not create multiple threads for timers. Each timer event that fires just puts an event into the event queue and if no JS is running at the time, that event is triggered (thus calling the callback function). If JS is running at the time, the JS engine waits until the currently executing JS finishes and then services the next event in the event queue (thus calling the callback).

这篇关于javascript中的递归setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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