dev /
(In)activity timer
Having an auto-rotating, 3 to 5 items promo carousel on a web page is a common practice. They work by continuously displaying a few items—one after another—within an interval of a few seconds, freezing their rotation on hover. Yet, regarding timing, a lot of them lack in design.
Setting up an x-seconds timer is more than fairly simple, however, the user interaction confuses some. Stopping and resetting the timer on mouse over and out can raise some question bubbles for some web developers (especially those who are used to copy-pasting pre-made scripts). I for one found myself doing this several times in the past but every time using an unique implementation, so I said I’d put something together to reuse in the future.
Further on, there are more ways to accomplish this. Let’s consider a 3-seconds timer, you have three common approach types:
- Unexpected premature - Script checks if mouse is over every loop and only advances otherwise. The first loop after mouse out will take place within the next 0 to 3 seconds.
- Fashionably late - Script saves the time of the last mouse over and compares it with the current one every loop, to be at least 3 seconds older. The first loop after mouse out will take place within the next 3 to 6 seconds.
- Perfect timing - Script stops the timer on mouse over and resets it on mouse out. The first loop after mouse out will takes place after exactly 3 seconds. This is extremely easy to do in languages like AS3, but not in JavaScript. It’s not native so you have to simulate this behavior, and this is where this post comes in.
Here’s a small JavaScript resource that simulates a proper timer (AS3 replica): code.ovidiu.ch/timer/. You can find the JS API there, along with a demo, but the download link is at the bottom of this post.
And a basic usage example:
// Instantiate the timer var timer = new Timer(3000); // Add the callback listener timer.addEventListener(TimerEvent.TIMER, function(e) { trace("iteration " + e.target.currentCount); }); // Start the timer timer.start(); // Then, when needed, stop it timer.stop();
There, another detail overlooked no more, mission accomplished!
© August 2010 Ovidiu Cherecheș
+Reply
Posted November 2011, by Valer