-1

I was asked in a phone interview to replicate Javascript's setInterval, clearInterval methods by writing my own. I am not allowed to use setTimeout or clearTimeout.

function setInterval(func, wait){
  var currentTime = Date.now();
  while(currentTime < wait){
   currentTime = Date.now() - currentTime;
  }

  if(currentTime >= wait) { 
    func();
  }
}

function clearInterval(myVar){
  myVar = undeclared;
}
12
  • 1
    What else are you allowed to use and what not? It's a pretty broad task. Commented Feb 11, 2018 at 19:44
  • @Bergi - you can use anything but setTimeout, clearTimeout Commented Feb 11, 2018 at 21:22
  • 1
    those people who are voting to close this question, I will keep re-posting it until I get an answer. The responses below are quite helpful for me and creative in their implementation. Commented Feb 11, 2018 at 21:23
  • Anything? What environment are we even talking about? Just require('timer') would be absolutely trivial. Commented Feb 11, 2018 at 21:32
  • Please don't repost it. If the question is off-topic, it will stay so - and "creative" tasks are not exactly making good questions Commented Feb 11, 2018 at 21:34

3 Answers 3

2
 function setTimeout(func, ms, ...args){
   const start = Date.now();

   (function check(){
      if(start + ms >= Date.now()){
         func(...args);
      } else {
         requestAnimationFrame(check);
     }
   })()
}

You might use a pseudorecursive function and requestAnimationFrame to do this. Based on this setTimeout implementation without window.setTimeout you cane easily implement a new setInterval ...

PS: in node you can use process.nectTick instead of requestAnimationFrame

Sign up to request clarification or add additional context in comments.

Comments

2

Another possibility is, taking example from here, the usage of Web Workers:

let mySetInterval = function(callback, timeout) {
    let blob = new Blob([ "self.addEventListener('message', function(e) { \
      let old_date = Date.now(); \
      while (Date.now() - old_date <= " + timeout + ") {}; \
      self.postMessage(true); \
    }, false);" ], { type: "text/javascript" });

    let worker = new Worker(window.URL.createObjectURL(blob));
    worker.addEventListener("message", function(e) {
        if (callback() === false) {
            return
        }
        mySetInterval(callback, timeout)
    }, false);
    worker.postMessage(true);
};

var a = 0;
mySetInterval(() => { if (a >= 10) { return false } else { console.log(a++) } }, 1000)
console.log(45);

Every 1 second it updates the variable a with +1.

Like you see, in this way it is non-blocking and it will stop when the variable a is 10.

To clear the "interval", in this case simply return false inside the callback. Obviously is not the same as the clearInterval function! Here there is not something like an ID such as for the setInterval function.

Comments

1

Hard Task, you can sort of do what setInterval and setTimeout do with requestAnimationFrame ? Not the same, but could do what you want to do.

var time;

function repeatOften() {
  $("<div />").appendTo("body");
  time = requestAnimationFrame(repeatOften);
}

$("#start").on("click", function() {
  time = requestAnimationFrame(repeatOften);
});

$("#stop").on("click", function() {
  cancelAnimationFrame(time);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.