Posted By

TimoZachi on 12/21/11


Tagged

speed second kilobytes dowload


Versions (?)

How to measure download speed (Kilobytes per second) in AS3


 / 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.

  1. var howManyTimes:Number = 3; //How many times per second the download speed will be traced
  2. var bytesLoaded:Number = 0; //don't change, necessary for calculation
  3. var lastTime:int = 0; //don't change, necessary for calculation
  4. var content:DisplayObject; //this variable will hold the content loaded
  5.  
  6. var loader:Loader = new Loader();
  7. loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, kbsPerSec);
  8. loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
  9. lastTime = getTimer();
  10. loader.load(new URLRequest("heavy_image.jpg"));
  11.  
  12. //kbsPerSec listens to ProgressEvent.PROGRESS and traces the download speed "howManyTimes" times per second
  13. function kbsPerSec(event:ProgressEvent):void
  14. {
  15. var time:int = getTimer();
  16. if(time - lastTime >= (1000/howManyTimes))
  17. {
  18. var kiloBytes:Number = (event.bytesLoaded - bytesLoaded)/1000;
  19. var timeInSecs:Number = (time - lastTime)/1000;
  20.  
  21. var kbsPerSecVal:Number = Math.floor(kiloBytes/timeInSecs);
  22. trace(kbsPerSecVal + " kbs/s");
  23. bytesLoaded = event.bytesLoaded;
  24. lastTime = getTimer();
  25. }
  26. }
  27.  
  28. function onComplete(event:Event):void
  29. {
  30. loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
  31. loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, kbsPerSec);
  32. content = loader.content;
  33. loader = null;
  34. this.addChild(content);
  35. }

Report this snippet  

You need to login to post a comment.