How to keep an indexeddb transaction alive?

In IndexedDB, transactions are automatically committed when all the requests associated with the transaction are successfully completed. If you want to keep a transaction alive for a longer period, you can use the setInterval function to periodically perform a trivial operation within the transaction. This prevents the transaction from timing out and being automatically committed.

Here’s a simple example in JavaScript:

// Opening a database
var request ='yourDatabase', 1);
var db;

request.onerror = function(event) {
    console.log('Error opening database');

request.onsuccess = function(event) {
    db =;
    // Start a transaction
    var transaction = db.transaction(['yourObjectStore'], 'readwrite');
    // Perform a trivial operation within the transaction periodically
    var keepAliveInterval = setInterval(function() {
        // Trivial operation (e.g., get or put operation)
        var objectStore = transaction.objectStore('yourObjectStore');
        var getRequest = objectStore.get('someKey');

        getRequest.onsuccess = function() {
            // Do something trivial with the result
            console.log('Transaction is still alive.');

        getRequest.onerror = function() {
            console.log('Error in trivial operation.');
    }, 5000); // Repeat every 5 seconds (adjust as needed)

    // Continue with your main transaction logic here...

    // For example, adding a record to the object store
    var mainOperation = transaction.objectStore('yourObjectStore').put('someValue', 'someKey');

    mainOperation.onsuccess = function() {
        console.log('Main operation completed.');

    mainOperation.onerror = function() {
        console.log('Error in main operation.');

    // Commit the transaction when everything is done
    transaction.oncomplete = function() {
        clearInterval(keepAliveInterval); // Stop the keep-alive interval
        console.log('Transaction committed.');

This example uses setInterval to perform a trivial operation (e.g., a get operation) within the transaction every 5 seconds. Adjust the interval as needed for your specific use case. Remember to clear the interval once the main transaction is completed (transaction.oncomplete).

Leave a Reply

Your email address will not be published. Required fields are marked *