linuxeasy
linuxeasy

Reputation: 6499

Whats wrong with setInterval() and clearInterval() in this javascript function? clearInterval returns undefined

I have the following code:

var focusIntervalObj = setInterval(function(){
            focusDelayCaused++;
            console.log(focusDelayCaused);
        }, 100);

clearInterval(focusIntervalObj);

I am have a firebug installed.

I am expecting this code to log the value of focusDelayCaused.

But when I execute, it doesn't do so, and also the clearInterval() simply returns undefined.

Please guide.

Upvotes: 0

Views: 620

Answers (3)

James
James

Reputation: 13501

Going on the code above, you're immediately clearing an interval just after you've set it. So it never has a chance to run.

Clearing the interval after some sort of condition has been met rather than immediately after setting it would help.

if (focusDelayCaused>50) {
  clearInterval(focusIntervalObj);
}

Upvotes: 1

Adilson de Almeida Jr
Adilson de Almeida Jr

Reputation: 2755

If you want some function be executed once and never again, use setTimeout, in your case:

var focusIntervalObj = setTimeout(function(){
            focusDelayCaused++;
            console.log(focusDelayCaused);
        }, 100);

Upvotes: 0

Joe
Joe

Reputation: 82614

You are setting the interval and clearing it before it fires.

var focusIntervalObj = setInterval(function(){
        focusDelayCaused++;
        console.log(focusDelayCaused);
        clearInterval(focusIntervalObj);
    }, 100);

That might be what you are thinking. Which would be simpler as:

var focusIntervalObj = setTimeout(function(){
        focusDelayCaused++;
        console.log(focusDelayCaused);
    }, 100);

Upvotes: 3

Related Questions