state: Use debounce to throttle saves

This commit is contained in:
Feross Aboukhadijeh
2016-09-21 11:46:00 -07:00
parent 853db922f1
commit 46e138a376
2 changed files with 5 additions and 11 deletions

View File

@@ -21,6 +21,7 @@
"capture-frame": "^1.0.0",
"chromecasts": "^1.8.0",
"create-torrent": "^3.24.5",
"debounce": "^1.0.0",
"deep-equal": "^1.0.1",
"dlnacasts": "^0.1.0",
"drag-drop": "^2.12.1",

View File

@@ -1,15 +1,18 @@
const appConfig = require('application-config')('WebTorrent')
const debounce = require('debounce')
const path = require('path')
const {EventEmitter} = require('events')
const config = require('../../config')
const migrations = require('./migrations')
const SAVE_THROTTLED_INTERVAL = 1000
const State = module.exports = Object.assign(new EventEmitter(), {
getDefaultPlayState,
load,
save,
saveThrottled
saveThrottled: debounce(save, SAVE_THROTTLED_INTERVAL)
})
appConfig.filePath = path.join(config.CONFIG_PATH, 'config.json')
@@ -199,7 +202,6 @@ function load (cb) {
// Write state.saved to the JSON state file
function save (state, cb) {
console.log('Saving state to ' + appConfig.filePath)
delete state.saveStateTimeout
// Clean up, so that we're not saving any pending state
const copy = Object.assign({}, state.saved)
@@ -229,12 +231,3 @@ function save (state, cb) {
else State.emit('savedState')
})
}
// Write, but no more than once a second
function saveThrottled (state) {
if (state.saveStateTimeout) return
state.saveStateTimeout = setTimeout(function () {
if (!state.saveStateTimeout) return
save(state)
}, 1000)
}