You are reading a single comment by @dave_irvine and its replies. Click here to read the full conversation.
  • Well, amusingly, my prints are actually throttled, I just didn't want to overcomplicate the code

    
    function throttle(func, wait, options) {
      var context, args, result;
      var timeout = null;
      var previous = 0;
      if (!options) options = {};
      var later = function() {
        previous = options.leading === false ? 0 : Date.now();
        timeout = null;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      };
      return function() {
        var now = Date.now();
        if (!previous && options.leading === false) previous = now;
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0 || remaining > wait) {
          if (timeout) {
            clearTimeout(timeout);
            timeout = null;
          }
          previous = now;
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        } else if (!timeout && options.trailing !== false) {
          timeout = setTimeout(later, remaining);
        }
        return result;
      };
    }
    
    
    function printDeviceData(device) {
      try {
        Bluetooth.println(JSON.stringify(device));
      } catch (err) {}
    }
    
    function getDevices() {
      const throttledPrint = throttle(printDeviceData, 1000);
      
      NRF.setScan(function(device) {
        if (device.name && device.name.indexOf('Puck.js') >= 0) {
          const data = device.data.toString().substr(-1);
    
          if (!devices[device.name]) {
            devices[device.name] = {
              name: device.name,
              rssi: device.rssi,
              data: data,
            };
          }
          
          const oldDevice = devices[device.name];
          
          if (device.rssi !== oldDevice.rssi) {
            devices[device.name].rssi = device.rssi;
            
            throttledPrint(devices[device.name]);
          }
        }
      });
    }
    
About

Avatar for dave_irvine @dave_irvine started