Tickers in JavaScript
Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
Tickers can be stopped like timers. Once a ticker is stopped it won’t execute any more callbacks. We’ll stop ours after 1600ms.
When we run this program the ticker should tick 3 times before we stop it.
In JavaScript, we use setInterval
to create a ticker-like behavior. The setInterval
function repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This is similar to a ticker in other languages.
We use setTimeout
to stop the ticker after a certain amount of time. The clearInterval
function is used to stop the execution of the interval set by setInterval
.
Note that JavaScript runs in a single-threaded environment, so this example doesn’t use true concurrency like the original example. However, it demonstrates a similar concept of periodic execution and stopping it after a certain time.