3

I'm using V8 in conjuction with c++ and native window setInterval functon is not defined.

What would be an algorythm to create something like native setInterval but in pure js?

Denis Matafonov
  • 2,684
  • 23
  • 30
  • Since JavaScript itself doesn't provide a way to add tasks to the event queue, there isn't anything you can do with "pure" JavaScript. Maybe have a look at the V8 API? – Felix Kling Dec 09 '16 at 18:19
  • Try look how nodejs implement the timers, maybe help you. – Rafael Dantas Dec 09 '16 at 18:23
  • Possible duplicate of [Implementing setTimeout() and setInterval() in pure JavaScript](http://stackoverflow.com/questions/35824722/implementing-settimeout-and-setinterval-in-pure-javascript). See also [How is asynchronous javascript interpreted and executed in Node.js?](http://stackoverflow.com/questions/36491385/how-is-asynchronous-javascript-interpreted-and-executed-in-node-js) – guest271314 Dec 09 '16 at 18:27
  • @RafaelDantas, in Node they use C functions for timers operations. https://github.com/nodejs/node-v0.x-archive/blob/master/lib/timers.js – Denis Matafonov Dec 09 '16 at 18:42
  • @DenisMatafonov i think that you cannot implement timers with pure js. – Rafael Dantas Dec 09 '16 at 19:40
  • related - https://stackoverflow.com/q/50665051/104380 – vsync Jun 03 '18 at 09:48

1 Answers1

2

Assuming setTimeout is available (not probable, but you did not specify that):

function setInterval(fn, t) {
  let id = {};

  function wrapper() {
    id.timeout = setTimeout(wrapper, t);
    fn.apply(this, arguments);
  }

  id.timeout = setTimeout(wrapper, t);

  return id;
}

function clearInterval(id) {
  clearTimeout(id.timeout);
}
Tobias
  • 7,723
  • 1
  • 27
  • 44