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

259
Views
SetTimeout recursive with arrow function

I would like to know if there is a way to use setTimeout recursive implements with an arrow function, in order to use this (refers to my class attribute for example) inside. Indeed, this = undefined when i declare my setTimeout with a normal function

I got :

public currentIndex: number = 0;

setTimeout(function run(){
    this.currentIndex++;
    console.log(this.currentIndex); // returns undefined
    setTimeout(run, 1000);
}, 1000)

Instead of :

setTimeout(() => {
    this.currentIndex++;
    console.log(this.currentIndex) // returns currentIndex value
    setTimeout( ?? , 1000) // What should i put instead of '??' ?
}, 1000)
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You could bind this first and then use this function for all calls.

function run(reference) {
    this.currentIndex++;
    console.log(this.currentIndex); // returns undefined
    setTimeout(reference, 1000, reference);
}

const runThis = run.bind(thisReference);

setTimeout(runThis, 1000, runThis);
about 4 years ago · Juan Pablo Isaza Report

0

Its because arrow function does not create new context inside arrow function body but normal function does. So this in arrow function refers to parent scope context but this in normal function refers to its own context.

about 4 years ago · Juan Pablo Isaza Report

0

This will create setTimeouts recursively

let currentIndex = 0;

const run = () => {
    setTimeout(() => {
        currentIndex++;
        console.log(currentIndex);
        run();
    }, 1000);
}

run();

but better approach may be (I don't know your use case, so it is just maybe) to use setInterval()

let currentIndex = 0;

const interval = setInterval(() => {
    currentIndex++;
    console.log(currentIndex);

    // stop interval
    if (currentIndex >= 10) {
        clearInterval(interval);
    }
}, 1000);

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!