1

I need to make 3 new tabs in my chrome extension with a delay of a couple seconds between each of the tabs creation, but when I use the chrome.tabs.create in a for loop for(i=0;i<3;i++) with the setTimeout(function() like so

for(i=0;i<3;i++){
    setTimeout(function() {
    search();
}, 5000);

It just waits for the Timeout to finish and then opens all 3 tabs at once. I have looked at Chrome extension: open tabs with delay but it is a different situation.

Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64
Joe Schroedl
  • 21
  • 1
  • 4

1 Answers1

3

Right now you're telling the browser to open all three tabs after 5 seconds.

If you'd like them to open one after another, you'd have to multiply the timeout by your iterator (+1, unless you want the first tab to open immediately), like so:

for(i=0; i<3; i++){
    setTimeout(function() {
       search();
    }, 5000 * (i + 1));
}
Destrictor
  • 31
  • 1
  • That does introduce a delay before the first tab opens but then it doesn't keep going after one tab is made. I don't know if it is a problem with my search function or if the problem is caused by the loop being activated from a button that is then closed. [Code](http://pastebin.com/qRTp60Gq) – Joe Schroedl Aug 11 '16 at 17:49
  • @JoeSchroedl, that's because your `search()` function executes too long, `setTimeout` means add the task onto the queue after a set number of milliseconds. If the queue is empty, then the code is executed immediately; if the queue is not empty (your search() function is still running), the code must wait its turn. – Haibara Ai Aug 12 '16 at 00:41
  • That may be so but what would take up so much of the queue that the code wouldn't continue? I have tried simpler functions inside the loop and all of them only happen once. – Joe Schroedl Aug 12 '16 at 04:13