0

When test code it's will setinterval by not to click and when i click <div onclick="clear()">CLEAR</div> it's not clearinterval too.

How can i do for setinterval when click <div onclick="test_fn()">TEST</div> and clearinterval when click <div onclick="clear()">CLEAR</div>

<div onclick="test_fn()">TEST</div>

<script>
var xxx = null;
xxx = window.setInterval(function test_fn(){
 test_xxx();
}, 5000);



function test_xxx(){
 alert("123456789");
}
</script>

<br>
<div onclick="clear()">CLEAR</div>

<script>function clear(){
 window.clearInterval(xxx);
}
</script>

1 Answers1

0
  • Put the logic for setInterval() in the onclick handler rather than outside of it.

  • Also change the clear() to any other name. As you are invoking document.clear() instead of your function. Is "clear" a reserved word in Javascript?

  • You can use fat arrow syntax => of ES6 to pass the callback function to setInterval().

<div onclick="test_fn()">TEST</div>
<br>
<div onclick="clear_fn()">CLEAR</div>

<script>
var xxx = null;
function test_fn(){
    alert('clicked');
    xxx = window.setInterval(() => {
     test_xxx();
   }, 5000);
}
function clear_fn(){
   alert('cleared')
   window.clearInterval(xxx);
}
function test_xxx(){
 alert("123456789");
}
</script>
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44