-3

I am trying to stop my setInterval() but nothing I tried has worked.

what do I need to put in my clearInterval to stop the setInterval() function from running.

html

<p>PLease enter a time(secs) interval to have the divs change colors.</p>
Interval: <input type='number' id='interval' min='1' required>
<input type='button' value='Set Time' onclick='setTime()'>
<br><br>
<p> click the button below to stop it.</p>
<button onclick="clearInterval(x)">Stop it</button>

javascript

function setTime(){
    var userTime = document.getElementById('interval').value * 1000;

    if (userTime != null && userTime > 0 ){
        var x = setInterval(colorChangeTime, userTime);
    } else {
        alert("Please enter a number"); 
    }

the only thing I get with clearInterval(x) is a console error "x is undefined". I have tried other various things but haven't gotten anything to work.

abc123
  • 17,855
  • 7
  • 52
  • 82
gatsby2748
  • 27
  • 6
  • 12
    `x` is _local_ variable of `setTime`, not accessible from outside of `setTime()` – Tushar Nov 23 '15 at 03:19
  • 2
    here's a little more about @Tushar's comment: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript And note that `setTime()` doesn't have a closing brace in the code you provided, which might just be an omission in the question. – Marc Nov 23 '15 at 03:21
  • By making `x` _global_, [Demo](https://jsfiddle.net/tusharj/9w7o62L6/) – Tushar Nov 23 '15 at 03:22

1 Answers1

1

You are saving the interval value in a local variable, thus it is not available outside the function. If you want it available in some other function so you can call clearInterval(), then you need to save it somewhere where it will be available, not in a local variable. Those options include a higher scoped, common variable, a property of some persistent object, etc...

For example:

var interval;
function setTime(){
    var userTime = document.getElementById('interval').value * 1000;

    if (userTime != null && userTime > 0 ){
        interval = setInterval(colorChangeTime, userTime);
    } else {
        alert("Please enter a number"); 
    }
}

function clearTime() {
    clearInterval(interval);
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979