Skip to content
This repository was archived by the owner on May 13, 2024. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions examples/keep_alive/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const connection = new WebSocket(`wss://ws.binaryws.com/websockets/v3?app_id=${a

const api = new DerivAPIBasic({ connection });

const keepAlive = () => {
const proposal = () => {
api.subscribe({
proposal: 1,
subscribe: 1,
Expand All @@ -18,17 +18,21 @@ const keepAlive = () => {
symbol: 'R_100',
barrier: '+0.1',
});
/*
* Send a ping ever 30 seconds to keep the connection alive, needs to use the same
* websocket connection as the one you want to maintain.
*/
};

const keepAliveRes = async (res) => {
// Send a ping every 30 seconds to keep the connection alive
// Needs to use the same websocket connection as the one you want to maintain.
const ping = () => {
setInterval(() => {
api.ping();
}, 30000);
};

const wsResponse = async (res) => {
const data = JSON.parse(res.data);
if (data.error !== undefined) {
console.log('Error: %s ', data.error.message);
connection.removeEventListener('message', keepAliveRes, false);
connection.removeEventListener('message', wsResponse, false);
await api.disconnect();
} else if (data.msg_type === 'proposal') {
console.log('Details: %s', data.proposal.longcode);
Expand All @@ -40,14 +44,15 @@ const keepAliveRes = async (res) => {
}
};

const checkSignal = async () => {
await keepAlive();
connection.addEventListener('message', keepAliveRes);
const checkSignal = () => {
proposal();
ping();
connection.addEventListener('message', wsResponse);
};

const endCall = () => {
connection.removeEventListener('message', keepAliveRes, false);
keepAlive().unsubscribe();
connection.removeEventListener('message', wsResponse, false);
proposal().unsubscribe();
};

const keep_alive_button = document.querySelector('#keep_alive');
Expand Down