Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I trying to wrap my head around setTimeout, but I can't get it to work properly.

I have set up an example here: http://jsfiddle.net/timkl/Fca2n/

I want a text to countdown after an anchor is clicked - but my setTimeout seems to fire at the same time, even though I've set the delay to 1 sec.

This is my HTML:

<a href="#">Click me!</a>

<span id="target"></span>

This is my JS:

$(document).ready(function() {


function foo(){

    writeNumber = $("#target");
    
    setTimeout(writeNumber.html("1"),1000);
    setTimeout(writeNumber.html("2"),1000);
    setTimeout(writeNumber.html("3"),1000);
    };

$('a').click(function() {
 foo();
});

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
444 views
Welcome To Ask or Share your Answers For Others

1 Answer

setTimeout takes a function as an argument. You're executing the function and passing the result into setTimeout (so the function is executed straight away). You can use anonymous functions, for example:

setTimeout(function() {
    writeNumber.html("1");
}, 1000);

Note that the same is true of setInterval.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...