title: How to make a Chrome Extension sleep for a time and post message on port
body: <p>In my extension, I want the extension wait for a time, because it changes something in the content and it mustn't be fast. 
  I am using a sleep function, it is just a loop that breaks when the time comes but it makes my computer really slow. 
  I used setTimeout method, but the extension says "port is not defined", because the code goes on when the setTimeout method is run, but I think the port stops connection. 
  So, do you have any idea how I can make the code sleep without ruining the computer?</p>
  
  <p>Sleep function</p>
  
  <pre><code>function sleep(milliseconds) {
  
    var start = new Date().getTime();
    for (var i = 0; i &lt; 1e7; i++) {
       for(var j=0;j&lt;10000000;j++)
          if ((new Date().getTime() - start) &gt; milliseconds){
              return;
      }
    }
  }
  </code></pre>
  
  <p>Port codes</p>
  
  <pre><code>chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "knockknock");
  
    port.onMessage.addListener(function(msg) {
      console.log("mesajjj");
      if (msg.joke == "Baslat"){
          setTimeout(firstwaiting, 5000);
          console.log("wait");
      }
    });
  
  });
  
  function firstwaiting(){
    port.postMessage({question: "waited"}); 
    console.log("waited, now goes on");
  }
  
  </code></pre>
  
  <p>I get the "port is not defined at firstwaiting" error using the second way with the setTimeout method.
  There is no problem in the connection, it works with sleep function but I need a better way.</p>
  
  <p>I expect to have a delay without using too much of effort. I am trying it for days, but I couldn't find a way even on the net. Thanks in advance.</p>