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

172
Views
How to call a setInterval function saved in a variable

I have a setInterval() function saved to a variable in order to able to clear it after with clearInterval().

  walkRight = setInterval(moveSnakeRight,1000) 
  walkLeft = setInterval(moveSnakeLeft, 1000)
  walkUp = setInterval(moveSnakeUp, 1000)
  walkDown = setInterval(moveSnakeDown, 1000) 

//and

      clearInterval(walkLeft)
      clearInterval(walkRight)
      clearInterval(walkUp)

My question is if there is any way to call the same SetInterval again , in this case , walkRight or walkLeft or walkUp. Any of them..

If I try walkRight() it won't work because it is not a function and if I try window.walkRight doesn't work either.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

The return value of setInterval is a number that identifies the interval solely for the purposes of clearing it.

There is no way to use that number to get any other information about the interval. You can't use it to determine what function was used to run the interval. You can't use it to call that function again.

If you want that information, you must store it separately.

For example:

const moveSnakeRight = () => {
  console.log('moving right');
};

class IntervalController {
  constructor(func) {
    this.func = func;
    this.start();
  }

  start() {
    if (typeof this.interval === "undefined") {
      this.interval = setInterval(this.func, 1000);
    }
  }

  stop() {
    clearInterval(this.interval);
    this.interval = undefined;
  }
}

const moveRightController = new IntervalController(moveSnakeRight);

document.querySelector('#start').addEventListener('click', () => moveRightController.start());

document.querySelector('#stop').addEventListener('click', () => moveRightController.stop());
<button id=start>Start</button>
<button id=stop>Stop</button>

about 4 years ago · Santiago Gelvez 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!