Open In App

JavaScript Atomics wait() Method

The Atomics.wait() in JavaScript is an in-built method that 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 that is either “ok”, “not-equal”, or “timed-out”. The integer typedarray, index, and 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 accepts four parameters as mentioned above and described below: 

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

The below programs illustrate Atomics.wait() method in JavaScript:

Example 1: This program illustrates the basic use of the Atomics.wait() method in JavaScript.




let buf = new SharedArrayBuffer(1024);
let 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

Example 2: This program illustrates the basic use of Atomics.wait() method in JavaScript.




let buf = new SharedArrayBuffer(1024);
let 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: 

We have a complete list of Javascript Atomics methods, to check those please go through the Javascript Atomics Complete Reference article.

Supported Browser:


Article Tags :