Q:

autosaving in chrome app (packaged app)

I'm developing a Chrome App (a.k.a. packaged app) where most of the work occurs in a textarea element, and I want to ensure that the user's work is automatically saved.
One impractical approach is to save the work in a file on every keystroke and other change to the textarea, with something like this:
$('#text').on("keypress paste cut change", function () {
    // ... save to file
});

But that's way too much overhead, so instead I just set a dirty flag, and now the question is to effect the save at appropriate times if the dirty flag is set. These are some appropriate times I've come up with, all of which are easily implemented:

Every minute, which is the smallest interval that chrome.alarms.onAlarm will allow.
When the user exits the app with the Quit item on the File menu.
When the user explicitly chooses the Save item on the File menu. (This might go away in the final version, but it's very handy during development.)

The problem is that there is no event available when the user closes the app or the whole browser. These events do exist in JavaScript, but they are specifically disallowed in Chrome Apps. The rationale, as I understand it, is that the Chrome developers don't want to provide this crutch, and instead want to encourage app developers to implement apps that save work continuously. Fine! I'm all for it.
Any ideas how to implement autosaving in Chrome Apps?
Update: I just took a look at Gliffy Diagrams, perhaps the most ambitious of the Chrome Apps so far, and it doesn't do any saving when it's closed via the app window or from the dock. It only does it when Close or Save is chosen from its file menu. That's essentially what my app does.

A:

You can use an normal JavaScript timer (say, 5 seconds) in the function where you're currently setting your dirty flag. Make the timer reset with each keypress, so that the autosave kicks in after 5 seconds of inactivity:
var inactiveTimer;

$('#text').on("keypress paste cut change", function () {
    clearTimeout(inactiveTimer);

    // save after 5 seconds, unless another keypress resets this timer
    inactiveTimer = setTimeout(saveText, 5000);
}

Thus, you only save when the user hasn't done anything for 5 seconds, instead of saving after every single keystroke. Obviously, this doesn't handle the case that the user closes the app 4 seconds after he finishes typing, but it's better than your option #1.

