1

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 Answer 1

3

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().

Sign up to request clarification or add additional context in comments.

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.