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

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

问题描述

我正在使用 NodeJs 并且需要调用一个无限函数,但我不知道什么是最佳性能.

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);

设置超时

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 中类似于应该处理的函数列表.当您调用 setTimeoutsetIntervalprocess.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.

如果您的函数需要处理例如 10 毫秒,而间隔将是您的 60 毫秒..

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

  • 带有 setInterval 的函数将按时间处理:0-10, 60-70, 120-130, ...(因此调用之间只有 50 毫秒的延迟)
  • 但是使用 setTimeout 它将是:
    • 如果你先调用 func: 0-10, 70-80, 140-150, 210-220, ...
    • 如果你先调用 setTimeout: 60-70, 130-140, 200-210, ...

    所以区别在于函数启动之间的延迟,这在某些基于间隔的系统中可能很重要,例如游戏、拍卖、股票市场等.

    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..

    祝你的递归好运:-)

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

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