11

I am making a javascript bookmarklet that resizes all images, periodically.

javascript: function x(){
    for(i=0;i<=document.getElementsByTagName('img').length;i++)
        document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);

But it runs only once. What is the problem here??

Shubham
  • 21,300
  • 18
  • 66
  • 89
  • What are you trying to accomplish? Also your for loop at the end probably meant to be `i++`. – BoltClock Dec 24 '10 at 04:08
  • 1
    You shouldn't do `i<=document.getElementsByTagName('img').length`. You're reselecting all the images in the document as many times as there are images. You should cache the selection. `var images = document.getElementsByTagName('img'); for( var i = 0, len = images.length; i < len; i++ )` Notice also that I did `<` instead of `<=` as well. – user113716 Dec 24 '10 at 04:21
  • seems kind of useless because if you don't stop the timer images will grow forever. – Michiel van der Blonk Feb 24 '18 at 12:59

6 Answers6

31

Are you looking for setInterval() instead of setTimeout() by any chance?

t = window.setInterval("x()",100);
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

Here is the same code properly indented for clarity

function x() {
    for(i=0;i<=document.getElementsByTagName('img').length;++)
        document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);

window.setTimout() executes the passed code only once because it is meant to. If you want to execute code more often, use window.setInterval().

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

Shouldn't it be i++ at the end of your for loop?

epaps
  • 516
  • 1
  • 8
  • 20
0

Also there is a syntax error.

for(i=0;i<=document.getElementsByTagName('img').length;i++)

miqbal
  • 2,213
  • 3
  • 27
  • 35
0

You need to put the...

t = window.setTimeout("x()",100);

inside the function x() brackets { } and it works with SetTimeout()

function x() {
    for(i=0;i<=document.getElementsByTagName('img').length;i++)
        document.getElementsByTagName('img')[i].width+=1;

t = window.setTimeout("x()",100);
};

    x();

void(0);

You can only call x() after all the images have been loaded on the page or there is an error.

gravityboy
  • 817
  • 5
  • 11
  • 21
-2

It might be window.setTimeOut("x",100)

Edit : correct the answer to this window.setTimeout(x,100).

PS: thats what happens if you simply work with a IDEs.

user113716
  • 318,772
  • 63
  • 451
  • 440
Biswanath
  • 9,075
  • 12
  • 44
  • 58