title: Google Script Separate Folders and Subfolders
body: <p>I'm a beginner coder and am using code I found on the internet to create a list of all folders and subfolders from a Google Drive folder. I'm able to generate that list, but I have two issues:</p>
  
  <p>How do I increase the run speed? I keep hitting the max of 6 minutes for executing a function.</p>
  
  <p>How can I tell the difference between a folder and subfolder? I can run the code and see the list of folders, but I would like a way to differentiate between what is a primary folder and what are the secondary folders within that folder before looking at a new one.</p>
  
  <p>I appreciate any help I can get.</p>
  
  <p>Heres the code I'm using</p>
  
  <pre><code>function listFolderContents() {
    var foldername = 'name of folder';
    var folderlisting = 'listing of folder ' + foldername;  
    var ss = SpreadsheetApp.create(folderlisting);
    var sheet = ss.getActiveSheet();
    var folders = DriveApp.getFoldersByName(foldername)
    var folder = folders.next();                  
    //listFilesInFolder(folder, sheet);
    traverseFolder(folder, sheet);
  };
  
  function traverseFolder(folder, sheet) { 
    listFilesInFolder(folder, sheet);  
    var subFolders = folder.getFolders();
    while (subFolders.hasNext()) {
      traverseFolder(subFolders.next(), sheet);
    }
  }
  
  function listFilesInFolder(folder, sheet) {
    var foldername = folder.getName();
    var contents = folder.getFiles();  
    sheet.appendRow( [foldername] );    
    while(contents.hasNext()) {
      var file = contents.next();   
    } 
  }
  </code></pre>