Skip to content
Related Articles

Related Articles

Improve Article

JavaScript | Atomics.wait() Method

  • Last Updated : 31 Mar, 2020

Among the Atomic Operations, there is an inbuilt operation Atomics.wait() in JavaScript is used to verify whether a given position in an Int32Array still contains a given value and if so sleeps, awaiting a wakeup or a timeout. The Atomics.wait() operation returns a string which is either “ok”, “not-equal”, or “timed-out”. The integer typedarray, index, and the value are passed as an argument to the function and timeout is also an argument but it is optional.

Syntax:

Atomics.wait(typedArray, index, value, timeout)

Parameters: This method accept four parameters as mentioned above and described below:

  • typedarray: This parameter specifies a shared integer typed array Int16Array.
  • index: This parameter specifies the position in the array, typedArray to wait on.
  • value: This parameter specifies the expected value to test.
  • timeout: This parameter is an optional parameter. It is time to wait in milliseconds.

Return value: The Atomics.wait() method returns the String which is either “ok”, “not-equal”, or “timed-out”.

Examples:



Input: arr[0] = 5
        Atomics.wait(arr, 0, 0, 1)
Output: not-equal

Input: arr[0] = 4
        Atomics.wait(arr, 1, 0, 1)
Output: time-out

Below programs illustrate the Atomics.wait() method in JavaScript:

Program 1:




var buf = new SharedArrayBuffer(1024); 
var arr = new Int32Array(buf); 
  
arr[0] = 5; 
console.log(Atomics.load(arr, 0)); 
console.log(Atomics.and(arr, 0, 9)); 
console.log(Atomics.wait(arr, 0, 0, 1)); 
console.log(Atomics.load(arr, 0)); 

Output:

5
5
not-equal
1

Program 2:




var buf = new SharedArrayBuffer(1024); 
var arr = new Int32Array(buf); 
  
arr[0] = 5; 
console.log(Atomics.load(arr, 0)); 
console.log(Atomics.and(arr, 0, 9)); 
console.log(Atomics.wait(arr, 1, 0, 1)); 
console.log(Atomics.load(arr, 0));

Output:

5
5
time-out
1

Exceptions:

  • If the typedArray is not a shared Int32Array then the Atomics.wait() operation throws a TypeError.
  • If the index used as an argument to the Atomics.wait() operation is out of the bound in the typedArray then the Atomics.store( ) operation throws a RangeError.
My Personal Notes arrow_drop_up
Recommended Articles
Page :