Disable timer within setInterval function with dyn

2019-06-05 18:16发布

问题:

I wanted to pass dynamic parameters into a setInterval function (see question here) and specifically @tvanfosson's comment. But now, I also want to disable that timer if a certain condition is met. I tried to define the timer variable as a global variable but I still get the timer as a undefined on this line:
console.log('else. timer=' + timer);:

else. timer=undefined

<script language="javascript" type="text/javascript">
    var timer;
    var params={};
    params.color='light';
    $(document).ready(function () {            
        timer=createInterval(showSmallWidget, params.color, 500);
    });

    function createInterval(f, dynamicParameter, interval) {
        setInterval(function () {
            f(dynamicParameter);
        }, interval);
    }

    function showSmallWidget(color) {
        if ($('#widget').html() == '') {
            //do stuff
        }
        else {
            console.log('else. timer=' + timer);
            if (timer) { console.log('CLEAR TIMER'); timer.clearInterval(); timer = null; }
        }
    }
</script>

I tried to create a JSFiddle, but I can't get it to work properly: https://jsfiddle.net/puhw3z2k/

回答1:

There are a couple problems:

1) You have to return the timerID from your createInterval() function:

function createInterval(f, dynamicParameter, interval) {
    return setInterval(function () {
        f(dynamicParameter);
    }, interval);
}

2) clearInterval() works like this clearInterval(timer), not timer.clearInterval().