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?
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); });
}
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With