DomainsFeatured DomainsFeatured - 1 year ago 89
Javascript Question

How To Add Delay To HTML Javascript Function

I have the following script that opens urls in a list:

function openWindow(){
var x = document.getElementById('a').value.split('\n');
for (var i = 0; i < x.length; i++)
if (x[i].indexOf('.') > 0)
if (x[i].indexOf('://') < 0)'http://'+x[i]);

However, I would like to add a delay (let's say about 5 seconds) between opening each url. How can I do this?

I'm not familiar with functions. Usually much better with Linux and such. Your insight is highly appreciated.

Answer Source

A better approach is to use setTimeout() along with a self-executing anonymous function:

function openWindow() {
    var i = 0;
    var x = document.getElementById('a').value.split('\n');
    (function() {
        if(typeof x[i] !== 'undefined') {
            if(x[i].indexOf('.') > 0) {
                if(x[i].indexOf('://') < 0) {
          'http://' + x[i++]);
                } else {
            setTimeout(arguments.callee, 1000);
        return false;

This will guarantee that the next call is not made before your code was executed. I used arguments.callee in this example as a function reference. Once the index no longer exists in the array, by checking if it's undefined, it simply returns false instead of setting another timout.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download