Namanyay Goel
Namanyay Goel

Reputation: 2660

Javascript - Need to use clearInterval outside setInterval function

Basically, what I have is a setInterval inside a function. What I want to do is, control it's behavior from outside.

Here's what I have -

function wheee() {
var i = 1;

slideee = setInterval(function() {
sliderContent.style.marginLeft = margin(i);
    if(i < imagesNoOneLess) {
        i++;
    } else {
        i = 0;
    }
}, 5000); }

Now, I want to clear the interval from outside the wheee() function. How can I do that?

I also want to run the interval again, from outside. How?

Upvotes: 2

Views: 2713

Answers (3)

Roy
Roy

Reputation: 428

Global variables are not dangerous, but a pretty way of coding it if you only have one slider is to use an object literal to simulate a singleton object.

var Slider= {
    slider: null,
    Start: function(i) {
        this.slider = setInterval(function() {
            // Slider code
            console.log('running: ' + i);
            i++;
        }, 1000);
    },
    Stop: function() {
        window.clearTimeout(this.slider);
    }
};

Slider.Start(1); // Start the slider
Slider.Stop(); // Stop the slider

Upvotes: 2

JNF
JNF

Reputation: 3730

Set the scope of slideee to be out of wheee.

Use objects in order to keep the global scope clean.

Upvotes: 1

Pointy
Pointy

Reputation: 413720

Well the way you've got the code now, it'll probably just work, because you didn't declare "slideee" with var.

As long as you somehow export the return value from setInterval() you're OK. You can either make that variable explicitly global (better than having it be implicit), or else have your "wheee" function return the value to its caller.

Upvotes: 2

Related Questions