Karol Jankiewicz Karol Jankiewicz - 3 months ago 16
Javascript Question

clearInterval and set it again after x seconds

I want to do simple interval with with if, he is checking a variable's value and doing a function again().

again function contains clearInterval, i++ and setTimeout to call interval again after x seconds

var speed = 1000;
var wait = 0;
var i = 0;

function init() {
setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}

function again(time) {
clearInterval(init());
i++;
setTimeout(function() {
setInterval(init(), speed);
}, time);
}
init();


I expect output like this:

1, 2, 3, _Waiting x sec's_ , 5, 1, 2, ...

but code doing some crazy things, he's going faster and faster. I don't know why.

Here's a codepen with example (can crash your browser!)

http://codepen.io/anon/pen/WxWzRz?editors=0010

Can you fix it and explain? Thanks

Answer

You are not clearing interval but use function inside clearInterval method. Method init which is used has no return statement so clearInterval gets undefined in attribute, so it is not clearing nothing.

Fixed code:

var speed = 1000;
var wait = 0;
var i = 0;
var interval=null;

function init() {
    interval = setInterval(function() {
        if (i >= 6) i = 0;
        if (i == 4) {
            wait = 5000;
            again(wait);
        } else {
            document.body.innerHTML = i;
            i++;
        }
    }, speed);
}

function again(time) {
    clearInterval(interval);
    i++;
    setTimeout(function() {

    init()

    }, time);
}

init();

Function setInterval returns interval id and function clearInterval in attribute should get id of interval which we want to stop, so I created interval variable to save id. I am using this variable in clearInterval.