fabio del carlo
fabio del carlo

Reputation: 23

Set interval with background image changing caused a lag

I'm trying to create an animation switching between 2 images used as the background image of a div here's my code:

var intervalloNavicella = setInterval(function() {
  if (accese == true) {
    var imageUrlSpacecrafat = "bk-nav-0" + currArea;
    $("#spacecraft").css(
      "background-image",
      "url(assets/img/" + imageUrlSpacecrafat + ".png)"
    );
    accese = false;
  } else {
    var imageUrlSpacecrafat = "bk-nav-0" + currArea + "-b";
    $("#spacecraft").css(
      "background-image",
      "url(assets/img/" + imageUrlSpacecrafat + ".png)"
    );
    accese = true;
  }
}, 500);

It works, the only problem is that during the changing sometimes there are some moments when the animation "lag" and there is no background image. This happens a lot of times and only for a few milliseconds. Is this a browser problem or this is about my code?

Upvotes: 0

Views: 310

Answers (2)

ElmirMahmudev
ElmirMahmudev

Reputation: 41

It could be because of high image quality. You can try to use 2 elements with loaded images, and toggle between them. Or decrease the quality of images.

Upvotes: 1

mplungjan
mplungjan

Reputation: 178094

Why not something like

var intervalloNavicella = setInterval(function(){ 
  $('#spacecraft').toggleClass("spacecraftb")
}, 500);
.spacecraft { 
  background-image : url(assets/img/bk-nav-0A.png);
}  

.spacecraftb { 
  background-image : url(assets/img/bk-nav-0B.png);
}  
<div id="spacecraft" class="spacecraft"></div>

Upvotes: 1

Related Questions