1

Im using java script in JSP the problem is i need auto refresh on selectin checkbox it's working fine but on unselecting it's not stopping the auto refresh activity .plz suggest Thanks in advance

function autorefresh() {
    var isChecked = document.getElementById("is_check").checked;
    var time = 0;
    if (isChecked == true) {
        time = setInterval(function () {
            showExport()
        }, 5000);
    } else if (isChecked == false) {
        clearInterval(time);
    }
}
8
  • 2
    Declare time outside of the function. Also note that you can reduce if (x == true) {...} else if (x == false) {...} to if (x) {...} else {...}. Commented Jan 28, 2014 at 6:13
  • @FelixKling - Why? And by the way @NaimFS, setInterval(function () { showExport() }, 5000); --> setInterval(showExport, 5000); Commented Jan 28, 2014 at 6:13
  • So that it persists between function calls. Commented Jan 28, 2014 at 6:15
  • @FelixKling - Is it because autorefresh is called multiple times? (although he never said it in his question or I missed it probably) Commented Jan 28, 2014 at 6:16
  • 1
    @Derek朕會功夫: Why, it makes total sense: If the checkbox is checked, start the interval. If it is unchecked, stop it, etc. Of course it should be reexecuted when the checkbox is checked again. Commented Jan 28, 2014 at 6:22

2 Answers 2

1

Define time variable as global:

window.time=0;     //global declaration
function autorefresh() {
    var isChecked = document.getElementById("is_check").checked;
    if (isChecked == true) {
        time = setInterval(function () {
            showExport()
        }, 5000);
    } else if (isChecked == false) {
        clearInterval(time);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

That's because you are defining the time variable inside the autorefresh context, so it no longer stores the ID of the interval, you should define it outside of the function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.