Sysadmin by day, developer by night

One of the things I do on unscatter.com is update timestamps for /facebook and /twitter results every 60 seconds. I like having the “Just Now” or “5 minutes ago” timestamps, but always want them to be representative of the actual time of the status message. This came from when I had a working Twitter/Facebook/Myspace client built into Unscatter.com. Something that will be built again by the way.

However, that operation can be a bit expensive depending on how many status messages are on the page. There’s also no point to doing it if the user isn’t looking at the page. So today, while working on the site I came up with a new way to do this. The idea is to only perform the operation if the window is in focus. At first I considered updating my updateTimestamps() function to check this. Then I realized setting up a tick that fires an event I can subscribe to would be even better. That way if I come up with other operations I want to do every 60 seconds, I can plug them in right away.

So, here’s the few lines of code necessary to make this happen with YUI3.


// ticker
var windowActive = 1;

win = Y.one(“window”);

win.on(“focus”, function(e) {
windowActive = 1;
});
win.on(“blur”, function(e) {
windowActive = 0;
});

tick = function() {
if (windowActive > 0) {
Y.Global.fire(“tick”);
}
}
setInterval( “tick()”, 60000 );

Then to update the timstamps every 60 seconds, I just need to call this.


Y.Global.on("tick", updateTimestamps);

Want to change the wallpaper every 60 seconds on the crazy Bing like page you’re working on?


Y.Global.on("tick", updateWallpaper);

Or check Twitter for your latest status message… whatever.

I’ll probably expand this in the future. Thinking about including the number of the minute it’s running on and firing an event for that as well. I’ll see about turning to into a proper synthetic event and submit it to the YUI Gallery if there’s interest.

  1. joerussbowman posted this
blog comments powered by Disqus
Technorati Profile