flash.utilsProxy The Proxy class lets you override the default behavior of ActionScript operations (such as retrieving and modifying properties) on an object.Object The Proxy class lets you override the default behavior of ActionScript operations (such as retrieving and modifying properties) on an object.

The Proxy class has no constructor, and you should not attempt to instantiate Proxy. Instead, subclass the Proxy class to override methods such as getProperty and provide custom behavior. If you try to use a method of the Proxy class without overriding the method, an exception is thrown.

And, keep in mind, your own code overriding the methods of the Proxy class can throw exceptions unintentionally. Throwing exceptions when using these methods causes problems because the calling code (using operators like in, is, delete and others) does not expect exceptions. Unless you're already sure your overriding method does not throw exceptions, Adobe recommends using try..catch statements around your implementation of the Proxy class to avoid fatal errors when operators call your methods. For example:

dynamic class MyProxy extends Proxy { flash_proxy override function callProperty(name:~~, ...rest):~~ { try { // custom code here } catch (e:Error) { // respond to error here } }

The Proxy class is a replacement for the Object.__resolve and Object.addProperty features of ActionScript 2.0, which are no longer available in ActionScript 3.0. The Object.addProperty() feature allowed you to dynamically create get and set methods in ActionScript 2.0. Although ActionScript 3.0 provides get and set methods at compile time, you cannot dynamically assign one to an object unless you use the Proxy class.

To avoid collisions with the public namespace, the methods of the Proxy class are in the flash_proxy namespace.

Where methods of the Proxy class take a name argument, name can be either a String or a QName object (if namespaces are being used).

package { import flash.display.Sprite; public class ProxyExample extends Sprite { public function ProxyExample() { var arr:ProxyArray = new ProxyArray(); arr.push(1); arr.push(-2); arr.push(3); arr.push(4); arr.push("five"); trace(arr.length); // 5 trace(arr[0]); // 1 trace(arr[1]); // -2 trace(arr[2]); // 3 trace(arr[3]); // 4 trace(arr.sum()); // 6 arr.clear(); trace(arr); // (empty string) arr[0] = "zero"; trace(arr); // zero } } } import flash.utils.Proxy; import flash.utils.flash_proxy; dynamic class ProxyArray extends Proxy { private var _item:Array; public function ProxyArray() { _item = new Array(); } override flash_proxy function callProperty(methodName:*, ... args):* { var res:*; switch (methodName.toString()) { case 'clear': _item = new Array(); break; case 'sum': var sum:Number = 0; for each (var i:* in _item) { // ignore non-numeric values if (!isNaN(i)) { sum += i; } } res = sum; break; default: res = _item[methodName].apply(_item, args); break; } return res; } override flash_proxy function getProperty(name:*):* { return _item[name]; } override flash_proxy function setProperty(name:*, value:*):void { _item[name] = value; } }
callProperty Overrides the behavior of an object property that can be called as a function.The return value of the called method. nameThe name of the method being invoked. restAn array specifying the arguments to the called method. Overrides the behavior of an object property that can be called as a function. When a method of the object is invoked, this method is called. While some objects can be called as functions, some object properties can also be called as functions. Function.call()ECMA-262 Language Specification, 3rd Edition, section 15deleteProperty Overrides the request to delete a property.If the property was deleted, true; otherwise false. BooleannameThe name of the property to delete. Overrides the request to delete a property. When a property is deleted with the delete operator, this method is called to perform the deletion. delete operatorECMA-262 Language Specification, 3rd Edition, 8.6.2.5getDescendants Overrides the use of the descendant operator.The results of the descendant operator. nameThe name of the property to descend into the object and search for. Overrides the use of the descendant operator. When the descendant operator is used, this method is invoked. descendant operatorE4X SpecificationgetProperty Overrides any request for a property's value.The specified property or undefined if the property is not found. nameThe name of the property to retrieve. Overrides any request for a property's value. If the property can't be found, the method returns undefined. For more information on this behavior, see the ECMA-262 Language Specification, 3rd Edition, section 8.6.2.1. get statementECMA-262 Language Specification, 3rd Edition, section 8.6.2.1hasProperty Overrides a request to check whether an object has a particular property by name.If the property exists, true; otherwise false. BooleannameThe name of the property to check for. Overrides a request to check whether an object has a particular property by name. Object.hasOwnProperty()ECMA-262 Language Specification, 3rd Edition, section 8.6.2.4isAttribute Checks whether a supplied QName is also marked as an attribute.Returns true if the argument for name is a QName that is also marked as an attribute. BooleannameThe name of the property to check. Checks whether a supplied QName is also marked as an attribute. QName classnextNameIndex Allows enumeration of the proxied object's properties by index number.The property's index value. intindexintThe zero-based index value where the enumeration begins. Allows enumeration of the proxied object's properties by index number. However, you cannot enumerate the properties of the Proxy class themselves. This function supports implementing for...in and for each..in loops on the object to retrieve property index values.

For example:

protected var _item:Array; // array of object's properties override flash_proxy function nextNameIndex (index:int):int { // initial call if (index == 0) { _item = new Array(); for (var x:~~ in _target) { _item.push(x); } } if (index < _item.length) { return index + 1; } else { return 0; } } override flash_proxy function nextName(index:int):String { return _item[index - 1]; }
Proxy.nextName()Proxy.nextValue()
nextName Allows enumeration of the proxied object's properties by index number to retrieve property names.The property's name. StringindexintThe zero-based index value of the object's property. Allows enumeration of the proxied object's properties by index number to retrieve property names. However, you cannot enumerate the properties of the Proxy class themselves. This function supports implementing for...in and for each..in loops on the object to retrieve the desired names.

For example (with code from Proxy.nextNameIndex()):

protected var _item:Array; // array of object's properties override flash_proxy function nextNameIndex (index:int):int { // initial call if (index == 0) { _item = new Array(); for (var x:~~ in _target) { _item.push(x); } } if (index < _item.length) { return index + 1; } else { return 0; } } override flash_proxy function nextName(index:int):String { return _item[index - 1]; }
Proxy.nextNameIndex()Proxy.nextValue()
nextValue Allows enumeration of the proxied object's properties by index number to retrieve property values.The property's value. indexintThe zero-based index value of the object's property. Allows enumeration of the proxied object's properties by index number to retrieve property values. However, you cannot enumerate the properties of the Proxy class themselves. This function supports implementing for...in and for each..in loops on the object to retrieve the desired values.

For example (with code from Proxy.nextNameIndex()):

protected var _item:Array; // array of object's properties override flash_proxy function nextNameIndex (index:int):int { // initial call if (index == 0) { _item = new Array(); for (var x:~~ in _target) { _item.push(x); } } if (index < _item.length) { return index + 1; } else { return 0; } } override flash_proxy function nextName(index:int):String { return _item[index - 1]; }
Proxy.nextNameIndex()Proxy.nextName()
setProperty Overrides a call to change a property's value.nameThe name of the property to modify. valueThe value to set the property to. Overrides a call to change a property's value. If the property can't be found, this method creates a property with the specified name and value. set statementECMA-262 Language Specification, 3rd Edition, section 8.6.2.2
ByteArray The ByteArray class provides methods and properties to optimize reading, writing, and working with binary data.flash.utils:IDataInputflash.utils:IDataOutputObject The ByteArray class provides methods and properties to optimize reading, writing, and working with binary data.

Note: The ByteArray class is for advanced developers who need to access data on the byte level.

In-memory data is a packed array (the most compact representation for the data type) of bytes, but an instance of the ByteArray class can be manipulated with the standard [] (array access) operators. It also can be read and written to as an in-memory file, using methods similar to those in the URLStream and Socket classes.

In addition, zlib compression and decompression are supported, as well as Action Message Format (AMF) object serialization.

Possible uses of the ByteArray class include the following:

  • Creating a custom protocol to connect to a server.
  • Writing your own URLEncoder/URLDecoder.
  • Writing your own AMF/Remoting packet.
  • Optimizing the size of your data by using data types.
  • Working with binary data loaded from a file in Adobe® AIR®.

The following example uses the class ByteArrayExample to write a Boolean and the double-precision floating-point representation of pi to a byte array. This is accomplished using the following steps:
  1. Declare a new ByteArray object instance byteArr.
  2. Write the byte-equivalent value of the Boolean false and then check the length and read it back.
  3. Write the double-precision floating-point equivalent of the mathematical value of pi.
  4. Read back each of the nine bytes written into the byte array.

Note: when trace() is called on a byte, it prints the decimal equivalent of the bytes stored in the byte array.

Notice how a code segment is added at the end to check for end of file errors to ensure that the byte stream is not read past its end.

package { import flash.display.Sprite; import flash.utils.ByteArray; import flash.errors.EOFError; public class ByteArrayExample extends Sprite { public function ByteArrayExample() { var byteArr:ByteArray = new ByteArray(); byteArr.writeBoolean(false); trace(byteArr.length); // 1 trace(byteArr[0]); // 0 byteArr.writeDouble(Math.PI); trace(byteArr.length); // 9 trace(byteArr[0]); // 0 trace(byteArr[1]); // 64 trace(byteArr[2]); // 9 trace(byteArr[3]); // 33 trace(byteArr[4]); // 251 trace(byteArr[5]); // 84 trace(byteArr[6]); // 68 trace(byteArr[7]); // 45 trace(byteArr[8]); // 24 byteArr.position = 0; try { trace(byteArr.readBoolean() == false); // true } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } try { trace(byteArr.readDouble()); // 3.141592653589793 } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } try { trace(byteArr.readDouble()); } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } } } }
[] (array access)Socket classURLStream classByteArray Creates a ByteArray instance representing a packed array of bytes, so that you can use the methods and properties in this class to optimize your data storage and stream. Creates a ByteArray instance representing a packed array of bytes, so that you can use the methods and properties in this class to optimize your data storage and stream. clear Clears the contents of the byte array and resets the length and position properties to 0. Clears the contents of the byte array and resets the length and position properties to 0. Calling this method explicitly frees up the memory used by the ByteArray instance. compress Compresses the byte array.algorithmStringunknownThe compression algorithm to use when compressing. Valid values are defined as constants in the CompressionAlgorithm class. The default is to use zlib format. This parameter is only recognized for content running in Adobe AIR. Flash Player supports only the default algorithm, zlib, and throws an exception if you attempt to pass a value for this parameter. Calling compress(CompressionAlgorithm.DEFLATE) has the same effect as calling the deflate() method. Compresses the byte array. The entire byte array is compressed. For content running in Adobe AIR, you can specify a compression algorithm by passing a value (defined in the CompressionAlgorithm class) as the algorithm parameter. Flash Player supports only the default algorithm, zlib.

After the call, the length property of the ByteArray is set to the new length. The position property is set to the end of the byte array.

The zlib compressed data format is described at http://www.ietf.org/rfc/rfc1950.txt.

The deflate compression algorithm is described at http://www.ietf.org/rfc/rfc1951.txt.

The deflate compression algorithm is used in several compression formats, such as zlib, gzip, some zip implementations, and others. When data is compressed using one of those compression formats, in addition to storing the compressed version of the original data, the compression format data (for example, the .zip file) includes metadata information. Some examples of the types of metadata included in various file formats are file name, file modification date/time, original file size, optional comments, checksum data, and more.

For example, when a ByteArray is compressed using the zlib algorithm, the resulting ByteArray is structured in a specific format. Certain bytes contain metadata about the compressed data, while other bytes contain the actual compressed version of the original ByteArray data. As defined by the zlib compressed data format specification, those bytes (that is, the portion containing the compressed version of the original data) are compressed using the deflate algorithm. Consequently those bytes are identical to the result of calling compress(air.CompressionAlgorithm.DEFLATE) on the original ByteArray. However, the result from compress(air.CompressionAlgorithm.ZLIB) includes the extra metadata, while the compress(CompressionAlgorithm.DEFLATE) result includes only the compressed version of the original ByteArray data and nothing else.

In order to use the deflate format to compress a ByteArray instance's data in a specific format such as gzip or zip, you cannot simply call compress(CompressionAlgorithm.DEFLATE). You must create a ByteArray structured according to the compression format's specification, including the appropriate metadata as well as the compressed data obtained using the deflate format. Likewise, in order to decode data compressed in a format such as gzip or zip, you can't simply call uncompress(CompressionAlgorithm.DEFLATE) on that data. First, you must separate the metadata from the compressed data, and you can then use the deflate format to decompress the compressed data.

uncompress()flash.utils.CompressionAlgorithm
deflate Compresses the byte array using the deflate compression algorithm. Compresses the byte array using the deflate compression algorithm. The entire byte array is compressed.

After the call, the length property of the ByteArray is set to the new length. The position property is set to the end of the byte array.

The deflate compression algorithm is described at http://www.ietf.org/rfc/rfc1951.txt.

In order to use the deflate format to compress a ByteArray instance's data in a specific format such as gzip or zip, you cannot simply call deflate(). You must create a ByteArray structured according to the compression format's specification, including the appropriate metadata as well as the compressed data obtained using the deflate format. Likewise, in order to decode data compressed in a format such as gzip or zip, you can't simply call inflate() on that data. First, you must separate the metadata from the compressed data, and you can then use the deflate format to decompress the compressed data.

inflate()
inflate Decompresses the byte array using the deflate compression algorithm.The data is not valid compressed data; it was not compressed with the same compression algorithm used to compress. IOErrorflash.errors:IOError Decompresses the byte array using the deflate compression algorithm. The byte array must have been compressed using the same algorithm.

After the call, the length property of the ByteArray is set to the new length. The position property is set to 0.

The deflate compression algorithm is described at http://www.ietf.org/rfc/rfc1951.txt.

In order to decode data compressed in a format that uses the deflate compression algorithm, such as data in gzip or zip format, it will not work to simply call inflate() on a ByteArray containing the compression formation data. First, you must separate the metadata that is included as part of the compressed data format from the actual compressed data. For more information, see the compress() method description.

deflate()
readBoolean Reads a Boolean value from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorReturns true if the byte is nonzero, false otherwise. Boolean Reads a Boolean value from the byte stream. A single byte is read, and true is returned if the byte is nonzero, false otherwise. readByte Reads a signed byte from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorAn integer between -128 and 127. int Reads a signed byte from the byte stream.

The returned value is in the range -128 to 127.

readBytes Reads the number of data bytes, specified by the length parameter, from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe value of the supplied offset and length, combined, is greater than the maximum for a uint. RangeErrorRangeErrorbytesflash.utils:ByteArrayThe ByteArray object to read data into. offsetuint0The offset (position) in bytes at which the read data should be written. lengthuint0The number of bytes to read. The default value of 0 causes all available data to be read. Reads the number of data bytes, specified by the length parameter, from the byte stream. The bytes are read into the ByteArray object specified by the bytes parameter, and the bytes are written into the destination ByteArray starting at the position specified by offset. readDouble Reads an IEEE 754 double-precision (64-bit) floating-point number from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA double-precision (64-bit) floating-point number. Number Reads an IEEE 754 double-precision (64-bit) floating-point number from the byte stream. readFloat Reads an IEEE 754 single-precision (32-bit) floating-point number from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA single-precision (32-bit) floating-point number. Number Reads an IEEE 754 single-precision (32-bit) floating-point number from the byte stream. readInt Reads a signed 32-bit integer from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA 32-bit signed integer between -2147483648 and 2147483647. int Reads a signed 32-bit integer from the byte stream.

The returned value is in the range -2147483648 to 2147483647.

readMultiByte Reads a multibyte string of specified length from the byte stream using the specified character set.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorUTF-8 encoded string. StringlengthuintThe number of bytes from the byte stream to read. charSetStringThe string denoting the character set to use to interpret the bytes. Possible character set strings include "shift-jis", "cn-gb", "iso-8859-1", and others. For a complete list, see Supported Character Sets.

Note: If the value for the charSet parameter is not recognized by the current system, the application uses the system's default code page as the character set. For example, a value for the charSet parameter, as in myTest.readMultiByte(22, "iso-8859-01") that uses 01 instead of 1 might work on your development system, but not on another system. On the other system, the application will use the system's default code page.

Reads a multibyte string of specified length from the byte stream using the specified character set.
readObject Reads an object from the byte array, encoded in AMF serialized format.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe deserialized object. Reads an object from the byte array, encoded in AMF serialized format. flash.net.registerClassAlias()readShort Reads a signed 16-bit integer from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA 16-bit signed integer between -32768 and 32767. int Reads a signed 16-bit integer from the byte stream.

The returned value is in the range -32768 to 32767.

readUTFBytes Reads a sequence of UTF-8 bytes specified by the length parameter from the byte stream and returns a string.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA string composed of the UTF-8 bytes of the specified length. StringlengthuintAn unsigned short indicating the length of the UTF-8 bytes. Reads a sequence of UTF-8 bytes specified by the length parameter from the byte stream and returns a string. readUTF Reads a UTF-8 string from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorUTF-8 encoded string. String Reads a UTF-8 string from the byte stream. The string is assumed to be prefixed with an unsigned short indicating the length in bytes. flash.utils.IDataInput.readUTF()readUnsignedByte Reads an unsigned byte from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA 32-bit unsigned integer between 0 and 255. uint Reads an unsigned byte from the byte stream.

The returned value is in the range 0 to 255.

readUnsignedInt Reads an unsigned 32-bit integer from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA 32-bit unsigned integer between 0 and 4294967295. uint Reads an unsigned 32-bit integer from the byte stream.

The returned value is in the range 0 to 4294967295.

readUnsignedShort Reads an unsigned 16-bit integer from the byte stream.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA 16-bit unsigned integer between 0 and 65535. uint Reads an unsigned 16-bit integer from the byte stream.

The returned value is in the range 0 to 65535.

toString Converts the byte array to a string.The string representation of the byte array. String Converts the byte array to a string. If the data in the array begins with a Unicode byte order mark, the application will honor that mark when converting to a string. If System.useCodePage is set to true, the application will treat the data in the array as being in the current system code page when converting. uncompress Decompresses the byte array.The data is not valid compressed data; it was not compressed with the same compression algorithm used to compress. IOErrorflash.errors:IOErroralgorithmStringunknownThe compression algorithm to use when decompressing. This must be the same compression algorithm used to compress the data. Valid values are defined as constants in the CompressionAlgorithm class. The default is to use zlib format. This parameter is only recognized for content running in Adobe AIR. Flash Player supports only the default algorithm, zlib, and throws an exception if you attempt to pass a value for this parameter. Decompresses the byte array. For content running in Adobe AIR, you can specify a compression algorithm by passing a value (defined in the CompressionAlgorithm class) as the algorithm parameter. The byte array must have been compressed using the same algorithm. Flash Player supports only the default algorithm, zlib.

After the call, the length property of the ByteArray is set to the new length. The position property is set to 0.

The zlib compressed data format is described at http://www.ietf.org/rfc/rfc1950.txt.

The deflate compression algorithm is described at http://www.ietf.org/rfc/rfc1951.txt.

In order to decode data compressed in a format that uses the deflate compression algorithm, such as data in gzip or zip format, it will not work to call uncompress(CompressionAlgorithm.DEFLATE) on a ByteArray containing the compression formation data. First, you must separate the metadata that is included as part of the compressed data format from the actual compressed data. For more information, see the compress() method description.

compress()flash.utils.CompressionAlgorithm
writeBoolean Writes a Boolean value.valueBooleanA Boolean value determining which byte is written. If the parameter is true, the method writes a 1; if false, the method writes a 0. Writes a Boolean value. A single byte is written according to the value parameter, either 1 if true or 0 if false. writeByte Writes a byte to the byte stream.valueintA 32-bit integer. The low 8 bits are written to the byte stream. Writes a byte to the byte stream.

The low 8 bits of the parameter are used. The high 24 bits are ignored.

writeBytes Writes a sequence of length bytes from the specified byte array, bytes, starting offset(zero-based index) bytes into the byte stream.bytesflash.utils:ByteArrayThe ByteArray object. offsetuint0A zero-based index indicating the position into the array to begin writing. lengthuint0An unsigned integer indicating how far into the buffer to write. Writes a sequence of length bytes from the specified byte array, bytes, starting offset(zero-based index) bytes into the byte stream.

If the length parameter is omitted, the default length of 0 is used; the method writes the entire buffer starting at offset. If the offset parameter is also omitted, the entire buffer is written.

If offset or length is out of range, they are clamped to the beginning and end of the bytes array.

writeDouble Writes an IEEE 754 double-precision (64-bit) floating-point number to the byte stream.valueNumberA double-precision (64-bit) floating-point number. Writes an IEEE 754 double-precision (64-bit) floating-point number to the byte stream. writeFloat Writes an IEEE 754 single-precision (32-bit) floating-point number to the byte stream.valueNumberA single-precision (32-bit) floating-point number. Writes an IEEE 754 single-precision (32-bit) floating-point number to the byte stream. writeInt Writes a 32-bit signed integer to the byte stream.valueintAn integer to write to the byte stream. Writes a 32-bit signed integer to the byte stream. writeMultiByte Writes a multibyte string to the byte stream using the specified character set.valueStringThe string value to be written. charSetStringThe string denoting the character set to use. Possible character set strings include "shift-jis", "cn-gb", "iso-8859-1", and others. For a complete list, see Supported Character Sets. Writes a multibyte string to the byte stream using the specified character set. writeObject Writes an object into the byte array in AMF serialized format.objectThe object to serialize. Writes an object into the byte array in AMF serialized format. flash.net.registerClassAlias()writeShort Writes a 16-bit integer to the byte stream.valueint32-bit integer, whose low 16 bits are written to the byte stream. Writes a 16-bit integer to the byte stream. The low 16 bits of the parameter are used. The high 16 bits are ignored. writeUTFBytes Writes a UTF-8 string to the byte stream.valueStringThe string value to be written. Writes a UTF-8 string to the byte stream. Similar to the writeUTF() method, but writeUTFBytes() does not prefix the string with a 16-bit length word. writeUTF Writes a UTF-8 string to the byte stream.If the length is larger than 65535. RangeErrorRangeErrorvalueStringThe string value to be written. Writes a UTF-8 string to the byte stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string. writeUnsignedInt Writes a 32-bit unsigned integer to the byte stream.valueuintAn unsigned integer to write to the byte stream. Writes a 32-bit unsigned integer to the byte stream. bytesAvailable The number of bytes of data available for reading from the current position in the byte array to the end of the array.uint The number of bytes of data available for reading from the current position in the byte array to the end of the array.

Use the bytesAvailable property in conjunction with the read methods each time you access a ByteArray object to ensure that you are reading valid data.

defaultObjectEncoding Denotes the default object encoding for the ByteArray class to use for a new ByteArray instance.uint Denotes the default object encoding for the ByteArray class to use for a new ByteArray instance. When you create a new ByteArray instance, the encoding on that instance starts with the value of defaultObjectEncoding. The defaultObjectEncoding property is initialized to ObjectEncoding.AMF3.

When an object is written to or read from binary data, the objectEncoding value is used to determine whether the ActionScript 3.0, ActionScript2.0, or ActionScript 1.0 format should be used. The value is a constant from the ObjectEncoding class.

ObjectEncoding classflash.utils.ByteArray.objectEncoding
endian Changes or reads the byte order for the data; either Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN.String Changes or reads the byte order for the data; either Endian.BIG_ENDIAN or Endian.LITTLE_ENDIAN. Endian classlength The length of the ByteArray object, in bytes.uint The length of the ByteArray object, in bytes.

If the length is set to a value that is larger than the current length, the right side of the byte array is filled with zeros.

If the length is set to a value that is smaller than the current length, the byte array is truncated.

objectEncoding Used to determine whether the ActionScript 3.0, ActionScript 2.0, or ActionScript 1.0 format should be used when writing to, or reading from, a ByteArray instance.uint Used to determine whether the ActionScript 3.0, ActionScript 2.0, or ActionScript 1.0 format should be used when writing to, or reading from, a ByteArray instance. The value is a constant from the ObjectEncoding class. ObjectEncoding classflash.utils.ByteArray.defaultObjectEncodingposition Moves, or returns the current position, in bytes, of the file pointer into the ByteArray object.uint Moves, or returns the current position, in bytes, of the file pointer into the ByteArray object. This is the point at which the next call to a read method starts reading or a write method starts writing.
IDataOutput The IDataOutput interface provides a set of methods for writing binary data. The IDataOutput interface provides a set of methods for writing binary data. This interface is the I/O counterpart to the IDataInput interface, which reads binary data. The IDataOutput interface is implemented by the FileStream, Socket and ByteArray classes.

All IDataInput and IDataOutput operations are "bigEndian" by default (the most significant byte in the sequence is stored at the lowest or first storage address), and are nonblocking.

Sign extension matters only when you read data, not when you write it. Therefore, you do not need separate write methods to work with IDataInput.readUnsignedByte() and IDataInput.readUnsignedShort(). In other words:

  • Use IDataOutput.writeByte() with IDataInput.readUnsignedByte() and IDataInput.readByte().
  • Use IDataOutput.writeShort() with IDataInput.readUnsignedShort() and IDataInput.readShort().
The following example uses the class DataOutputExample to write a boolean and the double-precision floating-point representation of pi to a byte array. This is accomplished using the following steps:
  1. Declare a new ByteArray object instance byteArr.
  2. Write the byte-equivalent value of the Boolean false and the double-precision floating-point equivalent of the mathematical value of pi.
  3. Read back the boolean and double-precision floating-point number.

Notice how a code segment is added at the end to check for end of file errors to ensure that the byte stream is not read past its end.

package { import flash.display.Sprite; import flash.utils.ByteArray; import flash.errors.EOFError; public class DataOutputExample extends Sprite { public function DataOutputExample() { var byteArr:ByteArray = new ByteArray(); byteArr.writeBoolean(false); byteArr.writeDouble(Math.PI); byteArr.position = 0; try { trace(byteArr.readBoolean()); // false } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } try { trace(byteArr.readDouble()); // 3.141592653589793 } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } try { trace(byteArr.readDouble()); } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } } } }
IDataInput interfaceendianFileStream classSocket classURLStream classByteArray classwriteBoolean Writes a Boolean value.valueBooleanA Boolean value determining which byte is written. If the parameter is true, 1 is written; if false, 0 is written. Writes a Boolean value. A single byte is written according to the value parameter, either 1 if true or 0 if false. writeByte Writes a byte.valueintA byte value as an integer. Writes a byte. The low 8 bits of the parameter are used; the high 24 bits are ignored. writeBytes Writes a sequence of bytes from the specified byte array, bytes, starting at the byte specified by offset (using a zero-based index) with a length specified by length, into the file stream, byte stream, or byte array.bytesflash.utils:ByteArrayThe byte array to write. offsetuint0A zero-based index specifying the position into the array to begin writing. lengthuint0An unsigned integer specifying how far into the buffer to write. Writes a sequence of bytes from the specified byte array, bytes, starting at the byte specified by offset (using a zero-based index) with a length specified by length, into the file stream, byte stream, or byte array.

If the length parameter is omitted, the default length of 0 is used and the entire buffer starting at offset is written. If the offset parameter is also omitted, the entire buffer is written.

If the offset or length parameter is out of range, they are clamped to the beginning and end of the bytes array.

writeDouble Writes an IEEE 754 double-precision (64-bit) floating point number.valueNumberA double-precision (64-bit) floating point number. Writes an IEEE 754 double-precision (64-bit) floating point number. writeFloat Writes an IEEE 754 single-precision (32-bit) floating point number.valueNumberA single-precision (32-bit) floating point number. Writes an IEEE 754 single-precision (32-bit) floating point number. writeInt Writes a 32-bit signed integer.valueintA byte value as a signed integer. Writes a 32-bit signed integer. writeMultiByte Writes a multibyte string to the file stream, byte stream, or byte array, using the specified character set.valueStringThe string value to be written. charSetStringThe string denoting the character set to use. Possible character set strings include "shift-jis", "cn-gb", "iso-8859-1", and others. For a complete list, see Supported Character Sets. Writes a multibyte string to the file stream, byte stream, or byte array, using the specified character set. writeObject Writes an object to the file stream, byte stream, or byte array, in AMF serialized format.objectThe object to be serialized. Writes an object to the file stream, byte stream, or byte array, in AMF serialized format. objectEncodingflash.net.registerClassAlias()writeShort Writes a 16-bit integer.valueintA byte value as an integer. Writes a 16-bit integer. The low 16 bits of the parameter are used; the high 16 bits are ignored. writeUTFBytes Writes a UTF-8 string.valueStringThe string value to be written. Writes a UTF-8 string. Similar to writeUTF(), but does not prefix the string with a 16-bit length word. writeUTF Writes a UTF-8 string to the file stream, byte stream, or byte array.If the length is larger than 65535. RangeErrorRangeErrorvalueStringThe string value to be written. Writes a UTF-8 string to the file stream, byte stream, or byte array. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string. writeUnsignedInt Writes a 32-bit unsigned integer.valueuintA byte value as an unsigned integer. Writes a 32-bit unsigned integer. endian The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant from the Endian class.String The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant from the Endian class. Endian classobjectEncoding Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the writeObject() method.uint Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the writeObject() method. The value is a constant from the ObjectEncoding class. IDataInput.readObject()writeObject()ObjectEncoding class
Endian The Endian class contains values that denote the byte order used to represent multibyte numbers.Object The Endian class contains values that denote the byte order used to represent multibyte numbers. The byte order is either bigEndian (most significant byte first) or littleEndian (least significant byte first).

Content in Flash Player or Adobe® AIR™ can interface with a server by using the binary protocol of that server, directly. Some servers use the bigEndian byte order and some servers use the littleEndian byte order. Most servers on the Internet use the bigEndian byte order because "network byte order" is bigEndian. The littleEndian byte order is popular because the Intel x86 architecture uses it. Use the endian byte order that matches the protocol of the server that is sending or receiving data.

flash.utils.ByteArray.endianflash.filesystem.FileStream.endianflash.utils.IDataInput.endianflash.utils.IDataOutput.endianflash.net.Socket.endianflash.net.URLStream.endianBIG_ENDIAN Indicates the most significant byte of the multibyte number appears first in the sequence of bytes.bigEndianString Indicates the most significant byte of the multibyte number appears first in the sequence of bytes.

The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent decimal number, 305419896, the most significant digit is 3, and the least significant digit is 6).

A stream using the bigEndian byte order (the most significant byte first) writes:

	 12 34 56 78
	 
LITTLE_ENDIAN Indicates the least significant byte of the multibyte number appears first in the sequence of bytes.littleEndianString Indicates the least significant byte of the multibyte number appears first in the sequence of bytes.

The hexadecimal number 0x12345678 has 4 bytes (2 hexadecimal digits per byte). The most significant byte is 0x12. The least significant byte is 0x78. (For the equivalent decimal number, 305419896, the most significant digit is 3, and the least significant digit is 6).

A stream using the littleEndian byte order (the least significant byte first) writes:

	 78 56 34 12
	 
IExternalizable The IExternalizable interface provides control over serialization of a class as it is encoded into a data stream. The IExternalizable interface provides control over serialization of a class as it is encoded into a data stream. The writeExternal() and readExternal() methods of the IExternalizable interface are implemented by a class to allow customization of the contents and format of the data stream (but not the classname or type) for an object and its supertypes. Each individual class must serialize and reconstruct the state of its instances. These methods must be symmetrical with the supertype to save its state. These methods supercede the native Action Message Format (AMF) serialization behavior.

If a class does not implement, nor inherits from a class which implements, the IExternalizable interface, then an instance of the class will be serialized using the default mechanism of public members only. As a result, private, internal, and protected members of a class will not be available.

To serialize private members, a class must use the IExternalizable interface. For example, the following class will not serialize any of its members because they are private:

class Example { private var one:int; private var two:int; }

However, if you implement the IExternalizable interface, you can write to, and read from, the data stream the private members of the class as follows:

class Example implement IExternalizable { private var one:int; private var two:int; public function writeExternal(output:IDataOutput) { output.writeInt(one); output.writeInt(two); } public function readExternal(input:IDataInput) { one = input.readInt(); two = input.readInt(); } }

Note: If a class implements IExternalizable the default serialization no longer applies to instances of that class. If that class inherits public members from a super class, you must carefully manage those members as well.

When a subclass of a class implementing IExternalizable has private members of its own, the subclass must override the methods of IExternalizable, as follows:

public class Base implements IExternalizable { private var one:Boolean; public function writeExternal(output:IDataOutput):void { output.writeBoolean(one); } public function readExternal(input:IDataInput):void { one = input.readBoolean(); } } public class Example extends Base { private var one:String; public override function writeExternal(output:IDataOutput):void { super.writeExternal(output); output.writeUTF(one); } public override function readExternal(input:IDataInput):void { super.readExternal(input); one = input.readUTF(); } }

The IExternalizable interface can also be used to compress data before writing it to a data stream. For example:

class Example implements IExternalizable { public var one:Boolean; public var two:Boolean; public var three:Boolean; public var four:Boolean; public var five:Boolean; public var six:Boolean; public var seven:Boolean; public var eight:Boolean; public function writeExternal(output:IDataOutput) { var flag:int = 0; if (one) flag |= 1; if (two) flag |= 2; if (three) flag |= 4; if (four) flag |= 8; if (five) flag |= 16; if (six) flag |= 32; if (seven) flag |= 64; if (eight) flag |= 128; output.writeByte(flag); } public function readExternal(input:IDataInput) { var flag:int = input.readByte(); one = (flag & 1) != 0; two = (flag & 2) != 0; three = (flag & 4) != 0; four = (flag & 8) != 0; five = (flag & 16) != 0; six = (flag & 32) != 0; seven = (flag & 64) != 0; eight = (flag & 128) != 0; } }
flash.net.ObjectEncodingreadExternal A class implements this method to decode itself from a data stream by calling the methods of the IDataInput interface.inputflash.utils:IDataInputThe name of the class that implements the IDataInput interface. A class implements this method to decode itself from a data stream by calling the methods of the IDataInput interface. This method must read the values in the same sequence and with the same types as were written by the writeExternal() method. writeExternal A class implements this method to encode itself for a data stream by calling the methods of the IDataOutput interface.outputflash.utils:IDataOutputThe name of the class that implements the IDataOutput interface. A class implements this method to encode itself for a data stream by calling the methods of the IDataOutput interface.
describeType Produces an XML object that describes the ActionScript object named as the parameter of the method.An XML object containing details about the object that was passed in as a parameter. It provides the following information about the object:
  • The class of the object
  • The attributes of the class
  • The inheritance tree from the class to its base classes
  • The interfaces implemented by the class
  • The declared instance properties of the class
  • The declared static properties of the class
  • The instance methods of the class
  • The static methods of the class
  • For each method of the class, the name, number of parameters, return type, and parameter types

Note: describeType() only shows public properties and methods, and will not show properties and methods that are private, package internal or in custom namespaces.

XML
valueThe object for which a type description is desired. Any ActionScript value may be passed to this method including all available ActionScript types, object instances, primitive types such as uint, and class objects.
Produces an XML object that describes the ActionScript object named as the parameter of the method. This method implements the programming concept of reflection for the ActionScript language.

If the value parameter is an instance of a type, the returned XML object includes all the instance properties of that type, but does not include any static properties. You can check for this condition when you parse the XML object by examining the value of the <type> tag's isStatic attribute, which is false when the value parameter is an instance of a type.

To obtain the static properties of a type, pass the type itself for the value parameter. The returned XML object includes not only the type's static properties, but also all of its instance properties. The instance properties are nested inside a tag named <factory> to distinguish them from the static properties. In this case, the isStatic attribute of the <type> tag is true.

Note: If you need only to traverse an object's inheritance hierarchy and do not need the other information provided by describeType(), use the getQualifiedClassName() and getQualifiedSuperclassName() functions instead.

The following table describes some of the tags and attributes of the XML object generated by describeType() (all class and interface names returned are in fully qualified format):

TagAttributeDescription<type> The root tag of the XML object. nameThe name of the ActionScript object's data type. baseThe immediate superclass of the ActionScript object's defining class. If the ActionScript object is a class object, the value is Class. isDynamictrue if the ActionScript object's defining class is dynamic; false otherwise. If the ActionScript object is a class object, the value is true because the Class class is dynamic. isFinaltrue if the ActionScript object's defining class is final; false otherwise. isStatictrue if the ActionScript object is a class object or constructor function; false otherwise. This attribute is named isStatic because if it is true, any tags that are not nested inside the factory tag are static.<extendsClass> There is a separate extendsClass tag for each superclass of the ActionScript object's defining class. typeThe name of a superclass that the ActionScript object's defining class extends.<implementsInterface> There is a separate implementsInterface tag for each interface implemented by the ActionScript object's defining class or any of its superclasses. typeThe name of an interface that the ActionScript object's defining class implements.<accessor> An accessor is a property defined by getter and setter functions. nameThe name of the accessor. accessThe access rights of the property. Possible values include readonly, writeonly, and readwrite. typeThe data type of the property. declaredByThe class that contains the associated getter or setter functions.<constant> A constant is a property defined with the const statement. nameThe name of the constant. typeThe data type of the constant.<method> A method is a function declared as part of a class definition. nameThe name of the method. declaredByThe class that contains the method definition. returnTypeThe data type of the method's return value.<parameter> There is a separate parameter tag for each parameter that a method defines. This tag is always nested inside a <method> tag. indexA number corresponding to the order in which the parameter appears in the method's parameter list. The first parameter has a value of 1. typeThe data type of the parameter. optionaltrue if the parameter is optional; false otherwise.<variable> A variable is a property defined with the var statement. nameThe name of the variable. typeThe data type of the variable.<factory> If the ActionScript object is a class object or constructor function, all instance properties and methods are nested inside this tag. If the isStatic attribute of the <type> tag is true, all properties and methods that are not nested within the <factory> tag are static. This tag appears only if the ActionScript object is a class object or constructor function.
package { import flash.display.Sprite; import flash.utils.describeType; public class DescribeTypeExample extends Sprite { public function DescribeTypeExample() { var child:Sprite = new Sprite(); var description:XML = describeType(child); trace(description..accessor.@name.toXMLString()); } } }
getQualifiedClassName()getQualifiedSuperclassName()
escapeMultiByte Returns an escaped copy of the input string encoded as either UTF-8 or system code page, depending on the value of System.useCodePage.An escaped copy of the input string. If System.useCodePage is true, the escaped string is encoded in the system code page. If System.useCodePage is false, the escaped string is encoded in UTF-8. For example, the input string "Crüe" will be escaped as "Cr%C3%BCe" on all systems if System.useCodePage is false. If system.useCodePage is true, and the system uses a Latin code page, "Crüe" will be escaped as "Cr%FCe". If the system uses a non Latin code page that does not contain the letter 'ü' the result will probably be "Cr?e". Unescaping "Cr%C3%BCe" with System.useCodePage set to true will produce different undesired results on different systems, such as "Crüe" on a Latin system. Similarly, unescaping "Cr%FCe" with System.useCodePage set to false could produce "Cre" or "Cr?e" or other variations depending on the code page of the system. StringvalueStringThe string to be escaped. Returns an escaped copy of the input string encoded as either UTF-8 or system code page, depending on the value of System.useCodePage. Use of System.useCodePage allows legacy content encoded in local code pages to be accessed by the runtime, but only on systems using that legacy code page. For example, Japanese data encoded as Shift-JIS will only be escaped and unescaped properly on an OS using a Japanese default code page. getDefinitionByName Returns a reference to the class object of the class specified by the name parameter.No public definition exists with the specified name. ReferenceErrorReferenceErrorReturns a reference to the class object of the class specified by the name parameter. ObjectnameStringThe name of a class. Returns a reference to the class object of the class specified by the name parameter. The following example uses the class GetDefinitionByNameExample to create an orange square on the stage. This is accomplished using the following steps:
  1. Variables for the background color of orange and size of 80 pixels are declared, which will later be used in drawing the square.
  2. Within the constructor, a variable ClassReference of type Class is assigned to Sprite.
  3. An instance of ClassReference called instance is instantiated.
  4. Since instance is, by reference, a Sprite object, a square can be drawn and added to the display list using the methods available to Sprite.
package { import flash.display.DisplayObject; import flash.display.Sprite; import flash.utils.getDefinitionByName; public class GetDefinitionByNameExample extends Sprite { private var bgColor:uint = 0xFFCC00; private var size:uint = 80; public function GetDefinitionByNameExample() { var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class; var instance:Object = new ClassReference(); instance.graphics.beginFill(bgColor); instance.graphics.drawRect(0, 0, size, size); instance.graphics.endFill(); addChild(DisplayObject(instance)); } } }
getQualifiedClassName Returns the fully qualified class name of an object.A string containing the fully qualified class name. StringvalueThe object for which a fully qualified class name is desired. Any ActionScript value may be passed to this method including all available ActionScript types, object instances, primitive types such as uint, and class objects. Returns the fully qualified class name of an object. describeType()getQualifiedSuperclassName()getQualifiedSuperclassName Returns the fully qualified class name of the base class of the object specified by the value parameter.A fully qualified base class name, or null if none exists. StringvalueAny value. Returns the fully qualified class name of the base class of the object specified by the value parameter. This function provides a quicker way of retrieving the base class name than describeType(), but also doesn't provide all the information describeType() does.

After you retrieve the name of a class with this function, you can convert the class name to a class reference with the getDefinitionByName() function.

Note: This function restricts itself to instance hierarchies, whereas the describeType() function uses class object hierarchies if the value parameter is a data type. Calling describeType() on a data type returns the superclass based on the class object hierarchy, in which all class objects inherit from Class. The getQualifiedSuperclassName() function, however, ignores the class object hierarchy and returns the superclass based on the more familiar instance hierarchy. For example, calling getQualifiedSuperclassName(String) returns Object although technically the String class object inherits from Class. In other words, the results are the same whether you use an instance of a type or the type itself.

describeType()getDefinitionByName()getQualifiedClassName()
getTimer Used to compute relative time.The number of milliseconds since the runtime was initialized (while processing ActionScript 2.0), or since the virtual machine started (while processing ActionScript 3.0). If the runtime starts playing one SWF file, and another SWF file is loaded later, the return value is relative to when the first SWF file was loaded. int Used to compute relative time. For a Flash runtime processing ActionScript 3.0, this method returns the number of milliseconds that have elapsed since the Flash runtime virtual machine for ActionScript 3.0 (AVM2) started. For a Flash runtime processing ActionScript 2.0, this method returns the number of milliseconds since the Flash runtime began initialization. Flash runtimes use two virtual machines to process ActionScript. AVM1 is the ActionScript virtual machine used to run ActionScript 1.0 and 2.0. AVM2 is the ActionScript virtual machine used to run ActionScript 3.0. The getTimer() method behavior for AVM1 is different than the behavior for AVM2.

For a calendar date (timestamp), see the Date object.

The following example uses the class GetTimerExample to get and print the number of milliseconds since the runtime initialized. package { import flash.utils.getTimer; import flash.display.Sprite; public class GetTimerExample extends Sprite { public function GetTimerExample() { var duration:uint = getTimer(); trace("duration: " + duration); } } }
flash.display.AVM1MovieDate class
unescapeMultiByte Returns an unescaped copy of the input string, which is decoded from either system code page page or UTF-8 depending on the value of System.useCodePage.An unescaped copy of the input string. If System.useCodePage is true, the escaped string is decoded from the system code page. If System.useCodePage is false, the escaped string is decoded from UTF-8. For example, if the input string is "Crüe" and System.useCodePage is false, the result will be "Crüe" on all systems. If System.useCodePage is true and the input string is "Cr%FCe", and the system uses a Latin code page, the result will also be "Crüe". Unescaping "Cr%C3%BCe" with System.useCodePage set to true will produce different undesired results on different systems, such as "Crüe" on a Latin system. Similarly, unescaping "Cr%FCe" with System.useCodePage set to false could produce "Cre" or "Cr?e" or other variations depending on the code page of the system. StringvalueStringThe escaped string to be unescaped. Returns an unescaped copy of the input string, which is decoded from either system code page page or UTF-8 depending on the value of System.useCodePage. Use of System.useCodePage allows legacy content encoded in local code pages to be accessed by the runtime, but only on systems using that legacy code page. For example, Japanese data encoded as Shift-JIS will only be escaped and unescaped properly on an OS using a Japanese default code page. clearInterval Cancels a specified setInterval() call.iduintThe ID of the setInterval() call, which you set to a variable, as in the following: Cancels a specified setInterval() call. The following example uses the setInterval() method to create a timed interval, calling the myRepeatingFunction() method after regular intervals of one second.

Each call of the myRepeatingFunction method increments the counter property, and when it equals the stopCount property, the clearInterval() method is called with the property intervalId which is a reference id to the interval that was created earlier.

package { import flash.display.Sprite; import flash.utils.*; public class ClearIntervalExample extends Sprite { private var intervalDuration:Number = 1000; // duration between intervals, in milliseconds private var intervalId:uint; private var counter:uint = 0; private var stopCount:uint = 3; public function ClearIntervalExample() { intervalId = setInterval(myRepeatingFunction, intervalDuration, "Hello", "World"); } public function myRepeatingFunction():void { trace(arguments[0] + " " + arguments[1]); counter++; if(counter == stopCount) { trace("Clearing Interval"); clearInterval(intervalId); } } } }
setInterval()
clearTimeout Cancels a specified setTimeout() call.iduintThe ID of the setTimeout() call, which you set to a variable, as in the following: Cancels a specified setTimeout() call. The following example uses the setTimeout() method to call another method following a specified delay period.

A loop is created to count to one million. If the system can process this request faster than a second can expire, clearTimeout() will remove the setTimeout() request, and myDelayedFunction() will not be called.

package { import flash.display.Sprite; import flash.utils.*; public class ClearTimeoutExample extends Sprite { private var delay:Number = 1000; // delay before calling myDelayedFunction private var intervalId:uint; private var count:uint = 1000000; public function ClearTimeoutExample() { intervalId = setTimeout(myDelayedFunction, delay); startCounting(); } public function startCounting():void { var i:uint = 0; do { if(i == count-1) { clearTimeout(intervalId); trace("Your computer can count to " + count + " in less than " + delay/1000 + " seconds."); } i++; } while(i < count) } public function myDelayedFunction():void { trace("Time expired."); } } }
setTimeout()
setInterval Runs a function at a specified interval (in milliseconds).Unique numeric identifier for the timed process. Use this identifier to cancel the process, by calling the clearInterval() method. uintclosureFunctionThe name of the function to execute. Do not include quotation marks or parentheses, and do not specify parameters of the function to call. For example, use functionName, not functionName() or functionName(param). delayNumberThe interval, in milliseconds. argumentsAn optional list of arguments that are passed to the closure function. Runs a function at a specified interval (in milliseconds).

Instead of using the setInterval() method, consider creating a Timer object, with the specified interval, using 0 as the repeatCount parameter (which sets the timer to repeat indefinitely).

If you intend to use the clearInterval() method to cancel the setInterval() call, be sure to assign the setInterval() call to a variable (which the clearInterval() function will later reference). If you do not call the clearInterval() function to cancel the setInterval() call, the object containing the set timeout closure function will not be garbage collected.

The following example uses the setInterval() method to create a timed interval, calling the myRepeatingFunction() method after regular intervals of one second. package { import flash.display.Sprite; import flash.utils.*; public class SetIntervalExample extends Sprite { private var intervalDuration:Number = 1000; // duration between intervals, in milliseconds public function SetIntervalExample() { var intervalId:uint = setInterval(myRepeatingFunction, intervalDuration, "Hello", "World"); } public function myRepeatingFunction():void { trace(arguments[0] + " " + arguments[1]); } } }
clearInterval()
setTimeout Runs a specified function after a specified delay (in milliseconds).Unique numeric identifier for the timed process. Use this identifier to cancel the process, by calling the clearTimeout() method. uintclosureFunctionThe name of the function to execute. Do not include quotation marks or parentheses, and do not specify parameters of the function to call. For example, use functionName, not functionName() or functionName(param). delayNumberThe delay, in milliseconds, until the function is executed. argumentsAn optional list of arguments that are passed to the closure function. Runs a specified function after a specified delay (in milliseconds).

Instead of using this method, consider creating a Timer object, with the specified interval, using 1 as the repeatCount parameter (which sets the timer to run only once).

If you intend to use the clearTimeout() method to cancel the setTimeout() call, be sure to assign the setTimeout() call to a variable (which the clearTimeout() function will later reference). If you do not call the clearTimeout() function to cancel the setTimeout() call, the object containing the set timeout closure function will not be garbage collected.

The following example uses the setTimeout() method to call another method following a specified delay period. package { import flash.display.Sprite; import flash.utils.*; public class SetTimeoutExample extends Sprite { private var delay:Number = 1000; // delay before calling myDelayedFunction public function SetTimeoutExample() { var intervalId:uint = setTimeout(myDelayedFunction, delay, "Hello", "World"); } public function myDelayedFunction():void { trace(arguments[0] + " " + arguments[1]); } } }
clearTimeout()
Timer The Timer class is the interface to timers, which let you run code on a specified time sequence.flash.events:EventDispatcher The Timer class is the interface to timers, which let you run code on a specified time sequence. Use the start() method to start a timer. Add an event listener for the timer event to set up code to be run on the timer interval.

You can create Timer objects to run once or repeat at specified intervals to execute code on a schedule. Depending on the SWF file's framerate or the runtime environment (available memory and other factors), the runtime may dispatch events at slightly offset intervals. For example, if a SWF file is set to play at 10 frames per second (fps), which is 100 millisecond intervals, but your timer is set to fire an event at 80 milliseconds, the event will be dispatched close to the 100 millisecond interval. Memory-intensive scripts may also offset the events.

The following example uses the class TimerExample to show how a listener method timerHandler() can be set to listen for a new TimerEvent to be dispatched. The timer is started when start() is called, and after that point, the timer events are dispatched. package { import flash.utils.Timer; import flash.events.TimerEvent; import flash.display.Sprite; public class TimerExample extends Sprite { public function TimerExample() { var myTimer:Timer = new Timer(1000, 2); myTimer.addEventListener("timer", timerHandler); myTimer.start(); } public function timerHandler(event:TimerEvent):void { trace("timerHandler: " + event); } } }
timerComplete Dispatched whenever it has completed the number of requests set by Timer.repeatCount.flash.events.TimerEvent.TIMER_COMPLETEflash.events.TimerEvent Dispatched whenever it has completed the number of requests set by Timer.repeatCount. timer Dispatched whenever a Timer object reaches an interval specified according to the Timer.delay property.flash.events.TimerEvent.TIMERflash.events.TimerEvent Dispatched whenever a Timer object reaches an interval specified according to the Timer.delay property. Timer Constructs a new Timer object with the specified delay and repeatCount states.if the delay specified is negative or not a finite number ErrorErrordelayNumberThe delay between timer events, in milliseconds. A delay lower than 20 milliseconds is not recommended. Timer frequency is limited to 60 frames per second, meaning a delay lower than 16.6 milliseconds causes runtime problems. repeatCountint0Specifies the number of repetitions. If zero, the timer repeats infinitely. If nonzero, the timer runs the specified number of times and then stops. Constructs a new Timer object with the specified delay and repeatCount states.

The timer does not start automatically; you must call the start() method to start it.

In the following example, the user is given 90 seconds to enter a response in an input text field. Also, every 30 seconds, a status message lets the user know how many seconds are left.

A Timer object is created that starts in 30 seconds (delay is set to 30000 milliseconds) and repeats three times, for a total of 90 seconds. (The timer stops after the third time.)

Two event listeners are added for the myTimer timer. The first is triggered by the TimerEvent.TIMER event, which occurs every time the timer is started. The timerHandler() method changes the text for the statusTextField text field to reflect the seconds remaining.

Note: The Timer class keeps track of the number of times it has to start (repeats) by increasing the number in the currentCount property.)

After the timer is called for the last time, the TimerEvent.TIMER_COMPLETE event is dispatched and the completeHandler() method is called. The completeHandler() method changes the type of the inputTextField text field from INPUT to DYNAMIC, which means the user can no longer enter or change text.

package { import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFieldType; import flash.text.TextFieldAutoSize; import flash.utils.Timer; import flash.events.TimerEvent; import flash.events.Event; public class Timer_constructorExample extends Sprite { private var statusTextField:TextField = new TextField(); private var inputTextField:TextField = new TextField(); private var delay:uint = 30000; private var repeat:uint = 3; private var myTimer:Timer = new Timer(delay, repeat); public function Timer_constructorExample() { inputTextField.x = 10; inputTextField.y = 10; inputTextField.border = true; inputTextField.background = true; inputTextField.height = 200; inputTextField.width = 200; inputTextField.multiline = true; inputTextField.wordWrap = true; inputTextField.type = TextFieldType.INPUT; statusTextField.x = 10; statusTextField.y = 220; statusTextField.background = true; statusTextField.autoSize = TextFieldAutoSize.LEFT; myTimer.start(); statusTextField.text = "You have " + ((delay * repeat) / 1000) + " seconds to enter your response."; myTimer.addEventListener(TimerEvent.TIMER, timerHandler); myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler); addChild(inputTextField); addChild(statusTextField); } private function timerHandler(e:TimerEvent):void{ repeat--; statusTextField.text = ((delay * repeat) / 1000) + " seconds left."; } private function completeHandler(e:TimerEvent):void { statusTextField.text = "Times Up."; inputTextField.type = TextFieldType.DYNAMIC; } } }
reset Stops the timer, if it is running, and sets the currentCount property back to 0, like the reset button of a stopwatch. Stops the timer, if it is running, and sets the currentCount property back to 0, like the reset button of a stopwatch. Then, when start() is called, the timer instance runs for the specified number of repetitions, as set by the repeatCount value. Timer.stop()start Starts the timer, if it is not already running. Starts the timer, if it is not already running. stop Stops the timer. Stops the timer. When start() is called after stop(), the timer instance runs for the remaining number of repetitions, as set by the repeatCount property. Timer.reset()currentCount The total number of times the timer has fired since it started at zero.int The total number of times the timer has fired since it started at zero. If the timer has been reset, only the fires since the reset are counted. delay The delay, in milliseconds, between timer events.NumberThrows an exception if the delay specified is negative or not a finite number. ErrorError The delay, in milliseconds, between timer events. If you set the delay interval while the timer is running, the timer will restart at the same repeatCount iteration.

Note: A delay lower than 20 milliseconds is not recommended. Timer frequency is limited to 60 frames per second, meaning a delay lower than 16.6 milliseconds causes runtime problems.

repeatCount The total number of times the timer is set to run.int The total number of times the timer is set to run. If the repeat count is set to 0, the timer continues forever or until the stop() method is invoked or the program stops. If the repeat count is nonzero, the timer runs the specified number of times. If repeatCount is set to a total that is the same or less then currentCount the timer stops and will not fire again. running The timer's current state; true if the timer is running, otherwise false.Boolean The timer's current state; true if the timer is running, otherwise false.
CompressionAlgorithm The CompressionAlgorithm class defines string constants for the names of compress and uncompress options.Object The CompressionAlgorithm class defines string constants for the names of compress and uncompress options. These constants are used as values of the algorithm parameter of the ByteArray.compress() and ByteArray.uncompress() methods. flash.utils.ByteArray.compress()flash.utils.ByteArray.uncompress()DEFLATE Defines the string to use for the deflate compression algorithm.deflateString Defines the string to use for the deflate compression algorithm. ZLIB Defines the string to use for the zlib compression algorithm.zlibString Defines the string to use for the zlib compression algorithm. IDataInput The IDataInput interface provides a set of methods for reading binary data. The IDataInput interface provides a set of methods for reading binary data. This interface is the I/O counterpart to the IDataOutput interface, which writes binary data.

All IDataInput and IDataOutput operations are "bigEndian" by default (the most significant byte in the sequence is stored at the lowest or first storage address), and are nonblocking. If insufficient data is available, an EOFError exception is thrown. Use the IDataInput.bytesAvailable property to determine how much data is available to read.

Sign extension matters only when you read data, not when you write it. Therefore you do not need separate write methods to work with IDataInput.readUnsignedByte() and IDataInput.readUnsignedShort(). In other words:

  • Use IDataOutput.writeByte() with IDataInput.readUnsignedByte() and IDataInput.readByte().
  • Use IDataOutput.writeShort() with IDataInput.readUnsignedShort() and IDataInput.readShort().
The following example uses the class DataInputExample to write a boolean and the double-precision floating-point representation of pi to a byte array. This is accomplished using the following steps:
  1. Declare a new ByteArray object instance byteArr.
  2. Write the byte-equivalent value of the Boolean false and the double-precision floating-point equivalent of the mathematical value of pi.
  3. Read back the boolean and double-precision floating-point number.

Notice how a code segment is added at the end to check for end of file errors to ensure that the byte stream is not read past its end.

package { import flash.display.Sprite; import flash.utils.ByteArray; import flash.errors.EOFError; public class DataInputExample extends Sprite { public function DataInputExample() { var byteArr:ByteArray = new ByteArray(); byteArr.writeBoolean(false); byteArr.writeDouble(Math.PI); byteArr.position = 0; try { trace(byteArr.readBoolean()); // false } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } try { trace(byteArr.readDouble()); // 3.141592653589793 } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } try { trace(byteArr.readDouble()); } catch(e:EOFError) { trace(e); // EOFError: Error #2030: End of file was encountered. } } } }
IDataOutput interfaceendianFileStream classSocket classURLStream classByteArray classEOFError classreadBoolean Reads a Boolean value from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA Boolean value, true if the byte is nonzero, false otherwise. Boolean Reads a Boolean value from the file stream, byte stream, or byte array. A single byte is read and true is returned if the byte is nonzero, false otherwise. readByte Reads a signed byte from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe returned value is in the range -128 to 127. int Reads a signed byte from the file stream, byte stream, or byte array. readBytes Reads the number of data bytes, specified by the length parameter, from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorbytesflash.utils:ByteArrayThe ByteArray object to read data into. offsetuint0The offset into the bytes parameter at which data read should begin. lengthuint0The number of bytes to read. The default value of 0 causes all available data to be read. Reads the number of data bytes, specified by the length parameter, from the file stream, byte stream, or byte array. The bytes are read into the ByteArray objected specified by the bytes parameter, starting at the position specified by offset. readDouble Reads an IEEE 754 double-precision floating point number from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorAn IEEE 754 double-precision floating point number. Number Reads an IEEE 754 double-precision floating point number from the file stream, byte stream, or byte array. readFloat Reads an IEEE 754 single-precision floating point number from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorAn IEEE 754 single-precision floating point number. Number Reads an IEEE 754 single-precision floating point number from the file stream, byte stream, or byte array. readInt Reads a signed 32-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe returned value is in the range -2147483648 to 2147483647. int Reads a signed 32-bit integer from the file stream, byte stream, or byte array. readMultiByte Reads a multibyte string of specified length from the file stream, byte stream, or byte array using the specified character set.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorUTF-8 encoded string. StringlengthuintThe number of bytes from the byte stream to read. charSetStringThe string denoting the character set to use to interpret the bytes. Possible character set strings include "shift-jis", "cn-gb", "iso-8859-1", and others. For a complete list, see Supported Character Sets.

Note: If the value for the charSet parameter is not recognized by the current system, then Adobe® Flash® Player or Adobe® AIR® uses the system's default code page as the character set. For example, a value for the charSet parameter, as in myTest.readMultiByte(22, "iso-8859-01"), that uses 01 instead of 1 might work on your development system, but not on another system. On the other system, Flash Player or the AIR runtime will use the system's default code page.

Reads a multibyte string of specified length from the file stream, byte stream, or byte array using the specified character set.
readObject Reads an object from the file stream, byte stream, or byte array, encoded in AMF serialized format.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe deserialized object Reads an object from the file stream, byte stream, or byte array, encoded in AMF serialized format. objectEncodingflash.net.registerClassAlias()readShort Reads a signed 16-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe returned value is in the range -32768 to 32767. int Reads a signed 16-bit integer from the file stream, byte stream, or byte array. readUTFBytes Reads a sequence of UTF-8 bytes from the byte stream or byte array and returns a string.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA UTF-8 string produced by the byte representation of characters of the specified length. StringlengthuintThe number of bytes to read. Reads a sequence of UTF-8 bytes from the byte stream or byte array and returns a string. readUTF Reads a UTF-8 string from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorA UTF-8 string produced by the byte representation of characters. String Reads a UTF-8 string from the file stream, byte stream, or byte array. The string is assumed to be prefixed with an unsigned short indicating the length in bytes.

This method is similar to the readUTF() method in the Java® IDataInput interface.

readUnsignedByte Reads an unsigned byte from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 255. uint Reads an unsigned byte from the file stream, byte stream, or byte array. readUnsignedInt Reads an unsigned 32-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 4294967295. uint Reads an unsigned 32-bit integer from the file stream, byte stream, or byte array. readUnsignedShort Reads an unsigned 16-bit integer from the file stream, byte stream, or byte array.There is not sufficient data available to read. EOFErrorflash.errors:EOFErrorThe returned value is in the range 0 to 65535. uint Reads an unsigned 16-bit integer from the file stream, byte stream, or byte array. bytesAvailable Returns the number of bytes of data available for reading in the input buffer.uint Returns the number of bytes of data available for reading in the input buffer. User code must call bytesAvailable to ensure that sufficient data is available before trying to read it with one of the read methods. endian The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant from the Endian class.String The byte order for the data, either the BIG_ENDIAN or LITTLE_ENDIAN constant from the Endian class. Endian classobjectEncoding Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the readObject() method.uint Used to determine whether the AMF3 or AMF0 format is used when writing or reading binary data using the readObject() method. The value is a constant from the ObjectEncoding class. readObject()IDataOutput.writeObject()ObjectEncoding class
Dictionary The Dictionary class lets you create a dynamic collection of properties, which uses strict equality (===) for key comparison.Object The Dictionary class lets you create a dynamic collection of properties, which uses strict equality (===) for key comparison. When an object is used as a key, the object's identity is used to look up the object, and not the value returned from calling toString() on it.

The following statements show the relationship between a Dictionary object and a key object:

 var dict = new Dictionary();
 var obj = new Object();
 var key:Object = new Object();
 key.toString = function() { return "key" }
 
 dict[key] = "Letters";
 obj["key"] = "Letters";
 
 dict[key] == "Letters"; // true
 obj["key"] == "Letters"; // true
 obj[key] == "Letters"; // true because key == "key" is true b/c key.toString == "key"
 dict["key"] == "Letters"; // false because "key" === key is false
 delete dict[key]; //removes the key
 
=== (strict equality)Dictionary Creates a new Dictionary object.weakKeysBooleanfalseInstructs the Dictionary object to use "weak" references on object keys. If the only reference to an object is in the specified Dictionary object, the key is eligible for garbage collection and is removed from the table when the object is collected. Creates a new Dictionary object. To remove a key from a Dictionary object, use the delete operator.