Problems with setInterval ()

1

I have the following code

var inter = setInterval(function(){
  plusDivs(1);
}, 2500);
$(".mySlides").mouseenter(function(){
  clearInterval(inter);
});
$(".mySlides").mouseleave(function(){
  var inter = setInterval(function(){
    plusDivs(1);
  }, 2500);
  console.log(inter);
});

In the above code, the inter variable is supposed to be a loop that stops when the cursor enters div . When I reload the page, the loop starts fine, when I move the cursor over, how it should be, how much I remove the div cursor, it starts but after it passes again, it does not stop and it retreats again, 2 loops start at the same time.

The slideshow was based here

    
asked by anonymous 19.12.2017 / 18:19

2 answers

2

The error is happening because you are redeclaring the inter variable.

When you define a variable outside the scope of the var inter = 0 function, it is global, and can be accessed through any other function.

When you define a variable within the scope of the function, it becomes local and can not be accessed outside the function.

// Global
var global = 0;

function myFunc() {
    // Local
    var local = 0;
}

The correct way is this:

var inter = setInterval(function(){
  plusDivs(1);
}, 2500);

$(".mySlides").mouseenter(function(){
  clearInterval(inter);
});

$(".mySlides").mouseleave(function(){
  inter = setInterval(function(){
    plusDivs(1);
  }, 2500);
  console.log(inter);
});

In your case, the best way to avoid this error is to use function to always assign a value to this variable. This will help you maintain the code in the medium / long term.

var inter = setInterval(function(){
  //plusDivs(1);
  $("#log").text("Loop running...")
}, 2500);

$(".mySlides").mouseenter(function(){
  clearInterval(inter);
  $("#log").text("Loop stoped.")
});

$(".mySlides").mouseleave(function(){
  inter = setInterval(function(){
    //plusDivs(1);
    $("#log").text("Loop running again...")
  }, 2500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="mySlides">.mySlides</div>
<div id="log"></div>
    
19.12.2017 / 18:38
0

The inter variable is global, can not be declared again, just assign the setinterval would look like this:

var inter = setInterval(function(){
  plusDivs(1);
}, 2500);
$(".mySlides").mouseenter(function(){
  clearInterval(inter);
});
$(".mySlides").mouseleave(function(){
  inter = setInterval(function(){ // aqui não se define novamente a variavel inter
    plusDivs(1);
  }, 2500);
  console.log(inter);
});
    
19.12.2017 / 18:31