Question

The problem is this: when you turn the checkbox, a timer is on, turn off the checkbox and timer goes off. I've tried, but nothing try.

        $('#apply').click(function () {


    if ($('#autoupdate').prop("checked")) {

            var timerId = setInterval(function () {
                $.ajax({
                    type: "post",
                    url: "1.php",
                    cache: false,
                    success: function (html) {
                        $("#result").html(html);
                    }
                });
            }, 1000);

    } else {clearInterval(timerId);}

    });


Autoupdate: <input type="checkbox" id="autoupdate">
<input id="apply" type="submit" value="Apply">
<div id="result"></div>
Was it helpful?

Solution

You have to declare variable outside. like

var timerId = 0;

and then put your code

var timerId= 0;
$('#apply').click(function () {


    if ($('#autoupdate').prop("checked")) {

            timerId = setInterval(function () {
                $.ajax({
                    type: "post",
                    url: "1.php",
                    cache: false,
                    success: function (html) {
                        $("#result").html(html);
                    }
                });
            }, 1000);

    } else {clearInterval(timerId);}

});

cause if it's declared inside if then accessing variable timerId from else will not be possible, cause its undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top