Phase 1: Use slideshow
When creating a webpage homepage, I want to use slideshow [1] for image switching. The js Code is as follows:
Copy codeThe Code is as follows:
Function next_slide (){
Var $ active = $ ('# bitware-overlay img. active ');
If ($ active. length = 0)
$ Active = $ ('# bitware-overlay img: la ');
Var $ next = $ active. next (). length? $ Active. next (): $ ('# bitware-overlay img: first ');
$ Active. addClass ('Last-activity ');
$ Next. addClass ('active ');
Export next.css ({opacity: 0.0 });
$ Next. animate ({opacity: 1.0}, 1500, function (){
$ Active. removeClass ();
});
}
$ (Function (){
SetInterval ("next_slide ()", 4000 );
});
Stage 2: discover problems
When the browser opens multiple tabs at the same time and stays on the tab page for a while, the manager finds that the picture is the last one, then it changes to the first image. After the change (with a light effect) is completed, it suddenly jumps to the last image. When I change:
Copy codeThe Code is as follows:
Function next_slide (){
Var $ active = $ ('# bitware-overlay img. active ');
If ($ active. length = 0)
$ Active = $ ('# bitware-overlay img: la ');
Var $ next = $ active. next (). length? $ Active. next (): $ ('# bitware-overlay img: first ');
$ Active. addClass ('Last-activity ');
$ Next. addClass ('active ');
Export next.css ({opacity: 0.0 });
$ Next. animate ({opacity: 1.0}, 1500 );
$ Active. removeClass ();
SetTimeout ("next_slide ()", 4000 );
}
$ (Function (){
SetTimeout ("next_slide ()", 4000 );
});
It is found that when you return to the page after staying on another tab, the image is displayed in the correct order and the interval is also correct. It is 4000 milliseconds, but when displayed, it is directly redirected, it does not fade out. It seems that the 1500 ms of animate does not start any effect. After a while, it will return to normal. However, the length of time for this phenomenon is proportional to the length of time for staying on another tab.
Stage 3: Solve the Problem
The final reason is found because jquery is essentially a single thread [2]. When it stays in another tab, the excessive backlog of next_silde () functions in the task is caused. The final solution [4] is as follows:
Copy codeThe Code is as follows:
Function next_slide (){
Var $ active = $ ('# bitware-overlay img. active ');
If ($ active. length = 0)
$ Active = $ ('# bitware-overlay img: la ');
Var $ next = $ active. next (). length? $ Active. next (): $ ('# bitware-overlay img: first ');
$ Active. addClass ('Last-activity ');
$ Next. addClass ('active ');
Export next.css ({opacity: 0.0 });
$ Next. animate ({opacity: 1.0}, 1500, function (){
$ Active. removeClass ();
SetTimeout ("next_slide ()", 4000 );
});
}
$ (Function (){
SetTimeout ("next_slide ()", 4000 );
});