开发者

Why setTimeout() function runs only once?

I am making a javascript bookmarklet that resizes all images, per开发者_如何学JAVAiodically.

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??


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

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


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().


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


Also there is a syntax error.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜