top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How do JavaScript timers work?

+9 votes
486 views

What is a drawback of JavaScript timers?

posted Feb 5, 2014 by Muskan

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes
 
Best answer

At a fundamental level it’s important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let’s start by examining the three functions to which we have access that can construct and manipulate timers.

var id = setTimeout(fn, delay); – Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
var id = setInterval(fn, delay); – Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
clearInterval(id);, clearTimeout(id); – Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.

Timers can be tricky to use since they operate within a single thread, thus events queue up waiting to execute.

answer Feb 6, 2014 by Amit Kumar Pandey
+2 votes

A block of JavaScript code is generally executed synchronously. But there are some JavaScript native functions (timers) which let us to delay the execution of arbitrary instructions:
• setTimeout()
• setInterval()
• requestAnimationFrame()
The setTimeout() function is commonly used if you wish to have your function called once after the specified delay. The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. The requestAnimationFrame() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame.

answer Feb 6, 2014 by Hiteshwar Thakur
...