In the first stage, try out slideshow When I was making a homepage, I wanted to use slideshow [1] for image switching effects. The js part of the code is as follows:
function next_slide() {
var $active = $('#bitware-overlay img.active ');
if ($active.length == 0)
$active = $('#bitware-overlay img:last');
var $next = $active.next().length ? $active.next() : $('#bitware-overlay img:first');
$active.addClass('last-active');
$next.addClass('active');
$next.css({opacity: 0.0});
$next.animate({opacity: 1.0}, 1500, function(){
$active.removeClass();
});
}
$(function() {
setInterval("next_slide()", 4000);
});
Second stage, discovery Problem There was no problem in the normal test when opening the page. Finally, the leader found that when the browser opened multiple tabs at the same time and stayed on the page in the tab for a period of time, the picture that appeared was the last picture. Then it changes to the first picture. As soon as the change (with a fade-in effect) is completed, it suddenly jumps to the last picture. When I change to:
function next_slide() {
var $active = $('#bitware-overlay img.active');
if ($active.length == 0)
$active = $('#bitware-overlay img:last');
var $next = $active.next().length ? $active.next() : $('#bitware-overlay img:first');
$active.addClass('last-active') ;
$next.addClass('active');
$next.css({opacity: 0.0});
$next.animate({opacity: 1.0}, 1500);
$ active.removeClass();
setTimeout("next_slide()", 4000);
}
$(function() {
setTimeout("next_slide()", 4000);
});
I found that after staying in other tabs, when I returned to the page, the pictures were displayed in the correct order and the interval was correct, 4000 milliseconds. However, when displayed, it was a direct jump. It's not fading the shape either, it seems like the 1500ms of animate has no effect whatsoever. It will return to normal after a while, but the duration of this phenomenon seems to be directly proportional to the length of time spent on other tabs.
The third stage, solving the problem
Finally found out that the reason is because the essence of jquery is single thread[2]. When staying in other tabs, the next_silde() function is backlogged in the task. Caused by too much. The final solution [4] found is as follows:
function next_slide () {
var $active = $('#bitware-overlay img.active');
if ($active.length == 0)
$active = $('#bitware-overlay img :last');
var $next = $active.next().length ? $active.next() : $('#bitware-overlay img:first');
$active.addClass(' last-active');
$next.addClass('active');
$next.css({opacity: 0.0});
$next.animate({opacity: 1.0}, 1500, function(){
$active.removeClass();
setTimeout("next_slide()", 4000);
});
}
$(function() {
setTimeout("next_slide()", 4000);
});