/ Published in: ActionScript 3
A simple snippet showing how to display download speed (Kilobytes per second or kbs/s) in flash timeline script (AS3). You can use Flash "Simulate Download" option for testing.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var howManyTimes:Number = 3; //How many times per second the download speed will be traced var bytesLoaded:Number = 0; //don't change, necessary for calculation var lastTime:int = 0; //don't change, necessary for calculation var content:DisplayObject; //this variable will hold the content loaded var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, kbsPerSec); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete); lastTime = getTimer(); loader.load(new URLRequest("heavy_image.jpg")); //kbsPerSec listens to ProgressEvent.PROGRESS and traces the download speed "howManyTimes" times per second function kbsPerSec(event:ProgressEvent):void { var time:int = getTimer(); if(time - lastTime >= (1000/howManyTimes)) { var kiloBytes:Number = (event.bytesLoaded - bytesLoaded)/1000; var timeInSecs:Number = (time - lastTime)/1000; var kbsPerSecVal:Number = Math.floor(kiloBytes/timeInSecs); trace(kbsPerSecVal + " kbs/s"); bytesLoaded = event.bytesLoaded; lastTime = getTimer(); } } function onComplete(event:Event):void { loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete); loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, kbsPerSec); content = loader.content; loader = null; this.addChild(content); }