Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <pre id='display-panel'></pre>
</body>
</html>
 
function getRandomInt(min, max) {
  return Math.random() * (max - min) + min;
}
const search = (word, callback) => {
  const results = ['foo', 'bar', 'baz', 'baz2', 'etc', 'etc2'];
  
  const numberOfResults = getRandomInt(1, results.length);
  const randomTimeout = getRandomInt(1, 4);
  
  setTimeout(() => {
    callback(null, results.slice(0, numberOfResults));
  }, randomTimeout);
};
const display = (data) => {
  console.log('display', data);
  const el = document.querySelector('#display-panel');
  const msg = (typeof data === 'string') ? data : data.join(', ');
  
  el.textContent = msg;
};
const displaySearchResults = (error, results) => {
  if (error) {
    display('Search failed, please retry later.');
  } else {
    display(results);
  }
};
const word = 'cats';
// will display random results each time
// uncomment to check
// search(word, displaySearchResults);
const searchWrapper = (word, callback) => {
  const key = `search-${word}`;
  const results = sessionStorage.getItem(key);
  
  if (results) {
    // keeping things asynchronous
    setTimeout(() => callback(null, results), 1);
  } else {
    search(word, (error, res) => {
      if (error) { return callback(error); }
      
      // keeping the results in cache
      sessionStorage.setItem(key, res);
      callback(null, res);
    });
  }
};
// will always display the same results because they are cached
searchWrapper('cats', displaySearchResults);
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
nodelandpro
0viewers