A Clock
Built with blockbuilder.org
A Clock
Built with blockbuilder.org
import { fetchUrl } from 'fetch'; | |
const registerLongPolling = () => { | |
let counter = 0; | |
fetchUrl('http://localhost:3000/longpolling', (error, meta, body) => { | |
if (error) { | |
return; | |
} | |
if (counter > 4) { |
// example below uses express.js | |
let counter = 0; | |
app.get('/longpolling', (req, res, next) => { | |
const delay = Math.random(); | |
setTimeout(() => { | |
res.send({ | |
random: delay, | |
sequence: counter | |
}); | |
counter++; |
// example below is using express and express-ws | |
app.ws('/websocket', (ws, req) => { | |
ws.on('message', (msg) => { | |
if (msg === 'A') { | |
ws.send('9'); | |
} | |
}); | |
}); |
const wsConnection = new WebSocket('ws://localhost:3000/websocket'); | |
wsConnection.onopen = () => { | |
console.log('websocket connection is opened') | |
wsConnection.send('A'); | |
}; | |
wsConnection.onmessage = event => { | |
if (event.data === '9') { | |
setTimeout(() => { |
/* On the server side, when get the request from eventSource, | |
* response with content type as 'text/event-stream', | |
* and write data in the format according to | |
* https://www.w3.org/TR/2009/WD-eventsource-20090421/ | |
*/ | |
const constructSSEMsg = (res, id, data) => { | |
res.write('id: ' + id + '\n'); | |
res.write('data: ' + data + '\n\n'); | |
}; |
const evtSource = new EventSource('/sse'); | |
evtSource.onmessage = event => { | |
try { | |
const jsonData = JSON.parse(event.data); | |
console.log(jsonData); | |
} catch (e) { | |
console.log(e); | |
} | |
} |
const throttle = (func, delay) => { | |
let executable = true; | |
return () => { | |
if (executable) { | |
func(); | |
executable = false; | |
setTimeout(() => { | |
executable = true; | |
}, delay); | |
} |
function functionsProcessor(funcArr, initValue, ...args) { | |
if(!funcArr.length) return initValue | |
var cur = funcArr.shift() | |
return functionsProcessor(funcArr, cur(initValue, ...args), ...args) | |
} | |
function functionsProcessor(funcArr, initValue, ...args) { | |
for(var i = 0; i < funcArr.length; i++){ | |
initValue = funcArr[i](initValue, ...args) | |
} |
var assert = require('assert') | |
function deepEqual(obj1, obj2){ | |
var keys1 = Object.keys(obj1) | |
var keys2 = Object.keys(obj2) | |
if(keys1.length !== keys2.length) return false | |
for(var key in obj1){ |