良好实践中有多少setIntervals太多了? [英] How many setIntervals is too many in good practice?

查看:72
本文介绍了良好实践中有多少setIntervals太多了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢用我的网站添加效果(不是太多),但我通常会有3-4个间隔。只是想知道是否有人知道我是否在伸展障碍,或者如果我想要的话我可以拥有更多吗?

I like to spice my sites up with effects (not too many) but i generally have 3-4 intervals going. Just wondering if anyone knows if i'm stretching barriers or can i have a lot more if i wanted?

推荐答案

我会建议任何setinterval太多,你应该总是使用settimeout。原因是javascript是单线程的。这意味着如果某些代码(可能是setinterval中的函数)阻止超时调用,则setinterval将继续发出对该函数的更多调用。如果间隔很小,可能导致函数调用堆积起来,导致很难找到/重现错误。

I would suggest any setinterval is too many, you should always use settimeout instead. The reason for this is that javascript is single threaded. This means that if some code (maybe the function in setinterval) blocks the timeout call, setinterval will continue to issue more calls to the function. With small intervals this can result in function calls stacking up causing EXTREMELY hard to find/reproduce bugs.

这里的最佳做法是在函数本身内使用settimeout。所以如果你以前有过:

Best practice here is to just use settimeout within the function itself. So if you previously had:

function foobar()
{
// do some stuff 
}
setInterval(foobar, 100)

您应该将其更改为:

function foobar()
{
//do some stuff
setTimeOut(foobar, 100)
}

这有一个额外的好处,你可以添加一些逻辑来检查如果你真的想再次运行这个功能。

This has the added benefit that you can add a bit of logic in to check if you actually want to run the function again.

这篇关于良好实践中有多少setIntervals太多了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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