title: Why is a second taking longer than a second?
body: <p>I'm trying to create a timer in Google Apps Script, such that when there is a number displayed on a cell, and I start the script, the script will automatically decrement that number once every second, until the value reaches zero.</p>
  
  <p>So I found <a href="https://stackoverflow.com/a/47766484/1907765">this answer on a related question</a>, and managed to implement code that does the same thing just fine. My one problem is that the code seems to run slowly - so that a second doesn't actually take a second. At a guess, it's between 1.5 to 2 seconds. This obviously isn't hugely ideal for a timer, and I'm wondering if it's a fixable problem. Is there a code optimization that might make my timer run on time, or something I've not factored in?</p>
  
  <p><a href="https://docs.google.com/spreadsheets/d/1kMNp7Wa1s9UxZnKZCsHfZA6dAoiICiIf5kJQA_u7Z-o/edit?usp=sharing" rel="nofollow noreferrer">Here's a link to a test spreadsheet</a>, with the code in the Script Editor (it's View Only for safety, but the spreadsheet can be copied.) A UI control should initiate the "Start Timer" function if you want to test it.</p>
  
  <p>Here's the full code:</p>
  
  <pre><code>var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  function onOpen() {
   var ui = SpreadsheetApp.getUi();
   ui.createMenu("Timer controls")
   .addItem("Start Timer", "startTimer")
   .addToUi();
  }
  
  function startTimer() {
    var timer = ss.getRangeByName("Timer");
    var timeval = timer.getValue();
    while (timeval &gt; 0) {
      timeval--;
      timer.setValue(timeval);
      SpreadsheetApp.flush();
      Utilities.sleep(1000);
    }
  }
  </code></pre>