Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Violation: 'setTimeout' handler took <N>ms

Tags:

javascript

The array contains random values like let checkTypes = ['a','b','c'];. (The length of the array is also random.)

And, The array tries to call a functionthis.switch() by the number of arrays.

So, My code is ...

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

The following error remains([Violation] 'setTimeout' handler took <N>ms) in the developer's tool console and feels that my code does not seem to work normally.

Can I change the code so that I don't get this error?

like image 302
Beagle Dev Avatar asked Nov 27 '19 06:11

Beagle Dev


2 Answers

For starters: Chrome violation : [Violation] Handler took 83ms of runtime

What this is saying is this.switch is taking "too long" for it to feel like a responsive application. You don't have to fix this for it to work if it is working well enough for you. It is trying to provide a profiling of places you might improve your app / code.

Here is a bit easier to understand version of your code:

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

This will result in the execution tree as follows:

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;

I think this could maybe be expressed with less confusion as :

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); });
}
like image 135
bobbysmith007 Avatar answered Oct 07 '22 11:10

bobbysmith007


The violation message is maybe due to the nested setTimeout. As you don't provide delay time here, the browser will execute the callbacks as soon as possible but with unpredictable behavior. Why not just write your code like that:

for (let i = 0; i < checkTypes.length; i++) {
   this.switch(checkTypes[i]);
   if (i > 0 && i < checkTypes.length) this.switch(checkTypes[i + 1]);
}
like image 2
Fabien Avatar answered Oct 07 '22 12:10

Fabien