违规:“setTimeout”处理程序花费了 <N> 毫秒

Bea*_*Dev 11 javascript

该数组包含随机值,如let checkTypes = ['a','b','c'];。(数组的长度也是随机的。)

并且,数组尝试this.switch()按数组的数量调用函数。

所以,我的代码是...

for (let i = 0; i <= checkTypes.length-1; i++) {
    window.setTimeout(() => {
       this.switch(checkTypes[i]);
       if (i != 0 && i != checkTypes.length -1) window.setTimeout(() => this.switch(checkTypes[i+1]))
    });
}
Run Code Online (Sandbox Code Playgroud)

[Violation] 'setTimeout' handler took <N>ms开发者的工具控制台中仍然存在以下错误(),感觉我的代码似乎无法正常工作。

我可以更改代码以免出现此错误吗?

bob*_*007 6

对于初学者: Chrome 违规:[违规] 处理程序花费了 83 毫秒的运行时间

这意味着 this.switch 花费了“太长的时间”,以至于感觉不到它是一个响应式应用程序。如果它对您来说工作得足​​够好,那么您不必修复它即可工作。它试图提供您可以改进应用程序/代码的地方的分析。

这是更容易理解的代码版本:

var start = 0, end = checkTypes.length-1;
for (let i = start, t,n; i <= end ; i++) {
    var t = checkTypes[i];
    var n = (i  > start  && i <= ) && checkTypes[i+1];
    window.setTimeout(() => { this.switch(x); });
    if(y) window.setTimeout(() => { this.switch(y); );
}
Run Code Online (Sandbox Code Playgroud)

这将导致执行树如下:

switch(arr[0]) i=0
switch(arr[1]) i=1
switch(arr[2]) i=2
switch(arr[2]) i=1
switch(arr[3]) i=3
switch(arr[3]) i=2
switch(arr[4]) i=4
switch(arr[4]) i=3

...
switch(arr[max-1]) i = max-1;
switch(arr[max]) i= max;
switch(arr[max]) i= max-1;
Run Code Online (Sandbox Code Playgroud)

我认为这可能可以更简洁地表达为:

var start = 0, end = checkTypes.length-1;
for (let i = start, t,n; i <= end ; i++) {
    var t = checkTypes[i];
    window.setTimeout(() => { this.switch(x); });
    if(i > 1) window.setTimeout(() => { this.switch(x); });
}
Run Code Online (Sandbox Code Playgroud)


小智 2

违规消息可能是由于嵌套的 setTimeout 造成的。由于您没有在此处提供延迟时间,浏览器将尽快执行回调,但行为不可预测。为什么不直接这样编写代码:

for (let i = 0; i < checkTypes.length; i++) {
   this.switch(checkTypes[i]);
   if (i > 0 && i < checkTypes.length) this.switch(checkTypes[i + 1]);
}
Run Code Online (Sandbox Code Playgroud)