1

The loop starts fine on mouseover, but it doesn't stop on mouseout! What am i doing wrong?

SCRIPT

<script type="text/javascript">
        function iniciarep(x) {
        var iddointervalo = setInterval(function(){ change(x); }, 500);
        }
        function terminarep() {
        clearInterval(iddointervalo);
        }
        function change(x) { 

**do stuff here (working fine)**

        }  
</script>

HTML

<img id="c3" src="letras/m1.svg" alt="m"  onmouseover='iniciarep(this);' onmouseout='terminarep();'>
  • 2
    Your variable `iddointervalo` only exists within the scope of `iniciarep`... – Simon MᶜKenzie Nov 24 '19 at 21:27
  • 2
    scope error, you only define your `idointervalo` inside your funciton, you cannot access it from inside `terminarep` function – Icepickle Nov 24 '19 at 21:27
  • 1
    Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Heretic Monkey Nov 24 '19 at 21:35

1 Answers1

5

You need a global variable, because the local one is not known later.

var iddointervalo;

function iniciarep(x) {
    iddointervalo = setInterval(function(){ change(x); }, 500);
}

function terminarep() {
    clearInterval(iddointervalo);
}
FZs
  • 16,581
  • 13
  • 41
  • 50
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392