Monkey Raptor

Thursday, November 6, 2014

JavaScript: Setting Dynamic Duration of setInterval

JavaScript has two timing methods:
  • setInterval(function[or]expression, duration)
    This will repetitively invoke a function or evaluate an expression with a given (static) duration (millisecond).
    To set different (dynamic) duration, we need to stop the current timer, using clearInterval(), then re-run the timer.
    I'll show you how I did it in the demo below.

  • setTimeout(function[or]expression, duration)
    This will delay a function call or an expression evaluation with a given duration (millisecond), for just one time (no repetition). The timeout can be reset with clearTimeout().
    We can also dynamically change the duration of this method.


This is the JavaScript I typed earlier.
You can examine the logic in it, I put bunch of comments:

In that coding, I reset the timer using clearInterval every time the the timer runs. Then, loop back to the outer function to restart the timer.
That way, we can set new different timer duration on each invocation.

HTML elements

The basic styling (CSS)

Why do I wanna create different duration?
Well, there's a lot of different answers to that.

But as for me, for my own discovery time.

  • The independent page of that demo over there
  • The other hilarious example using both setInterval and setTimeout, but with additional thingies, at Thor
  • The neato answer about setting dynamic duration using setTimeout timing method on Stack Overflow
JavaScript: Setting Dynamic Duration of setInterval

No comments

Post a Comment

Tell me what you think...