[英]Efficient function declaration in JavaScript
我有一些需要每6秒运行一次的javascript代码,如下所示:
this.y = function()
{
//some logic that may or may not call y_a or y_b
this.y_a = function()
{
//some logic
}
this.y_b = function()
{
//some logic
}
var self = this;
setTimeout(function(){ self.y(); }, 6000);
}
y
的范围之外不需要y_a
和y_b
。
由于每6秒调用一次此函数,因此继续重新声明y_a
和y_b
效率很低吗? 还是应该在y
范围之外定义它们?
由于每6秒调用一次此函数,因此继续重新声明
y_a
和y_b
效率很低吗?
可能不是。 用计算机术语来说,两次通话之间的间隔非常长,为六秒钟。
还是应该在
y
范围之外定义它们?
可能是这样,除非您有充分的理由每次都要重新定义它们。
执行JS时,范围越近,解析速度越快。 据说6秒是CPU时间的永恒。
我将其编码为:
function y () {
function a() {..}
function b() {..}
//calling a and b
}
setInterval(y, 6000); // timeout is for one execution, interval for recurrent executions
是的,继续重新声明y_a和y_b效率不高。 正如Crowder早已指出的那样,6秒钟的时间间隔不会真正减慢。
就是说,我认为您使用的是错误的模式。 而是去做这样的事情:
y = (function()
{
//we create the functions inside this anonymous scope
function y_a()
{
//do stuff
}
function y_b()
{
//do stuff
}
//we return a function, that in its turn has access to the scope
//were the above funcs are delared. They are however hidden for the outside
return function()
{
if ( a )
{
y_a();
} else
{
y_b();
}
}
})();
setTimeout(function(){ y(); }, 6000);
如果要在6秒的间隔内调用该函数,则最好使用setInterval()。 因为setTimeout仅在超时后执行一次。
如果有选择,请在y之外声明函数y_a和y_b,然后添加:
function y_a() {
}
function y_b() {
}
function y() {
y_a();
y_b();
//calling y_a and y_b
}
window.setInterval(y,6000) // 6 secs = 6000 ms
对于刷新页面时的初始调用,您需要在ready()中调用该函数。 然后,每6秒钟将自动调用该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.