递归函数vs setInterval vs setTimeout javascript [英] recursive function vs setInterval vs setTimeout javascript

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

问题描述

我正在使用NodeJ并需要调用无限函数,但我不知道什么是最佳性能。

i am using NodeJs and need call a infinite function, but i dont know what is the best for a optimal performance.

递归函数

function test(){
//my code
test();
}

setInterval

setInterval(function(){
//my code
},60);

setTimeout

function test(){
//my code
setTimeout(test,60);
}

我想要最好的性能而不会崩溃服务器。我的代码有几个算术运算。

I want the best performance without collapse the server. My code have several arithmetic operations.

感谢任何优化javascript性能的建议。

appreciate any suggestions to optimize the javascript performance.

推荐答案

小心..你的第一个代码会阻止JavaScript事件循环。

Be carefull.. your first code would block JavaScript event loop.

JS基本上就像应该处理的函数列表。当你打电话给 setTimeout setInterval process.nextTick 你将给定的函数添加到此列表中,当正确的时间到来时,它将被处理..

Basically in JS is something like list of functions which should be processed. When you call setTimeout, setInterval or process.nextTick you will add given function to this list and when the right times comes, it will be processed..

你的代码在第一种情况下永远不会停止所以它永远不会让另一个要处理的事件列表中的函数。

Your code in the first case would never stop so it would never let another functions in the event list to be processed.

第二个和第三个案例是好的......但差别不大。

Second and third case is good.. with one little difference.

如果你的函数需要处理例如10ms而间隔将是你的60ms ..

If your function takes to process for example 10ms and interval will be yours 60ms..


  • 具有setInterval的函数将被处理多次: 0-10,60-70,120-130,......(所以它之间的延迟只有50ms)

  • 但是使用setTimeout它将是:

    • 如果您先调用func:0-10,70-80,140-150,210-220,...

    • 如果您先调用setTimeout:60 -70,130-140,200-210,...

    所以差异是你的功能开始之间的延迟,这在一些人中很重要基于terval的系统,如游戏,拍卖,股票市场......等。

    So the difference is delay between starts of your function which can be important in some interval based systems, like games, auctions, stock market.. etc..

    祝你的递归好运: - )

    Good luck with your recursion :-)

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

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