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

228
Views
Number of times the callback needs to be called before executed

I got presented 4 interview questions and one of them is this:

Write a function after that takes the number of times the callback needs to be called before being executed as the first parameter and the callback as the second parameter.

function after(count, func) {
  // Implement the 'after' function
}

var called = function() { console.log("hello") };
var afterCalled = after(3, called);

afterCalled(); // -> nothing is printed
afterCalled(); // -> nothing is printed
afterCalled(); // -> 'hello' is printed

The way I solved the problem is this:

function after(count, cBack) {
  localStorage.setItem("aCount", count);
  return function () {
    let currCount = localStorage.getItem("aCount");

    if (currCount == 1) {
      cBack();
    } else {
      localStorage.setItem("aCount", --currCount);
    }
  };
}

let called = function () {
  console.log("hello");
};

let afterCalled = after(5, called);

afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();

I mean, the code works as intended but I have a feeling that localStorage is not the way. Am I missing somethig? Is there something in callback functions that I can use or I 'should' use to solve this problem? If so, what should I look up?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

They probably expected you to use the closure formed by calling after (see comments):

let after = (count, callback) => {
    return () => {
        // Has our count reached one?
        if (count <= 1) {
            // Yes, call the callback
            callback();
        } else {
            // No, decrement the count
            --count;
        }
    };
};

let called = function () {
  console.log('hello')
};

let afterCalled = after(5, called);

afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();

The count parameter continues to exist as long as the function that after returns exists, because the function after returns is a closure over the context where it was created. So you can use that to remember the number of times called.

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!