54

Implement setInterval with setTimeout

 4 years ago
source link: https://www.tuicool.com/articles/vqABnen
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

setInterval vs setTimeout

  • setTimeout : sets a timer which executes a function or specified piece of code once the timer expires.
  • setInterval : repeatedly calls a function or executes a code snippet, with a fixed time delay between each call

setInterval can be implemented as recurisve setTimeout calls.

setInterval implementation with setTimeout

with signature

function _setInterval(fn: Function, delay: number): number;

The call stack will be:

--delay--> fn() --delay--> fn() --delay--> fn() ...

To delay the execution of fn , we could simply use setTimeout . Therefore, we create a wrapper function which encapsulates the logic which executes the original function.

function _setInterval(fn, delay) {
  // wrap the original function, recursively call the wrapper function with setTimeout 
  const wrapper = () => {
    fn();
    return setTimeout(wrapper, delay)
  }

  setTimeout(wrapper, delay);
}

_setInterval(console.log.bind(null, 'hello world'), 1000);

Notice

  • If you want to follow the latest news/articles for the series of my blogs, Please 「Watch」 to Subscribe.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK