0

Functions like setTimeout,setInterval etc. which are part of the browser(and not of JS engine) are asynchronous in nature, what are some other built-in functions or methods that are asynchronous, which are either part of JS engine or of a browser?

Also is it possible to implement something like setTimeout from with just javascript without using any browser APIs?

shafkathullah
  • 313
  • 5
  • 16
  • `fetch()` and promises are asynchronous – charlietfl Jul 12 '20 at 02:29
  • 1
    setTimeout and setInterval are javascript things, not browser APIs. – ray Jul 12 '20 at 02:30
  • @rayhatfield I mean they are not part of javascript engine, its implemented by browser venders. – shafkathullah Jul 12 '20 at 02:31
  • how about Node.js? https://nodejs.org/en/docs/guides/timers-in-node/ – The KNVB Jul 12 '20 at 02:33
  • I think I get what you mean, in that js is single threaded so it has to be handled by the environment, but they’re part of the js spec; any valid js engine implementation has to provide them. They’re available in node, for example. – ray Jul 12 '20 at 02:34
  • 1
    @rayhatfield it says they are not https://stackoverflow.com/questions/8852198/settimeout-if-not-defined-in-ecmascript-spec-where-can-i-learn-how-it-works – shafkathullah Jul 12 '20 at 02:36
  • @TheKNVB node.js reimplemented setTimeout etc, and its part of Node runtime and not of V8 engine which they use. V8 don't have these functions, neither do any JS engine I guess. – shafkathullah Jul 12 '20 at 02:39
  • 2
    I stand corrected. Always thought it was part of the spec. – ray Jul 12 '20 at 02:40

1 Answers1

-1

//setTimeout function without in-built function
let sleep = (interval) => {
    const previousTime = Date.now()
  while(Date.now() - previousTime < interval){
    //do nothing
  }
}

let mySetTimeout = (interval, func) => {
    sleep(interval)
  func()
}

let greet = () => {
    console.log("Hi")
}

mySetTimeout(5000, greet)