Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
JavaScript Scoping Can't Access setInterval

Hey guys can someone just quickly help me out here.

I have an interval for a slideshow in one function and I want to clear it from another function without using global scopes as I know it is bad practice.

Can someone kindly help here please?

function beginSlideshow() {
    var interval = setInterval(function () {
      //Slideshow content here
}

function revertSlideshow() {
    clearInterval(interval);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have to store the timer handle somewhere. :-)

You have lots of options:

Modules

You could use modules. Then a top-level declaration of interval wouldn't be a global, it would only be accessible to the module:

let interval = 0;
export function beginSlideshow() {
    interval = setInterval(function () {
        //Slideshow content here
    }, someValue);
}

export function revertSlideshow() {
    clearInterval(interval);
    interval = 0;
}

In a closure's scope

Similar concept to the module above, but without using modules:

const { beginSlideshow, revertSlideshow } = (() => {
    let interval = 0;
    function beginSlideshow() {
        interval = setInterval(function () {
            //Slideshow content here
        }, someValue);
    }

    function revertSlideshow() {
        clearInterval(interval);
        interval = 0;
    }

    return { beginSlideshow, revertSlideshow };
})());

In the caller's scope

You could make this the problem of the person calling beginSlideshow by returning the function to stop it:

function beginSlideshow() {
    const interval = setInterval(function () {
        //Slideshow content here
    }, someValue);
    return () => {
        clearInterval(interval);
    };
}

The caller would use that like this:

const revertSlideshow = beginSlideShow();
// ...
revertSlideshow();

Another way to store it in the caller's scope is to wrap this up in a class and have the handle be a data property:

class Slideshow {
    interval = 0;

    begin() {
        this.interval = setInterval(/*...*/);
    }

    revert() { // I'd call it "end"
        clearInterval(this.interval);
        this.interval = 0;
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!