Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  172] [ 4]  / answers: 1 / hits: 67549  / 13 Years ago, sat, november 19, 2011, 12:00:00

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();
});

});

More From » jquery

 Answers
23

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.


[#89013] Friday, November 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mari

Total Points: 305
Total Questions: 100
Total Answers: 98

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
mari questions
Mon, Feb 18, 19, 00:00, 5 Years ago
Wed, Jan 2, 19, 00:00, 6 Years ago
Tue, Dec 25, 18, 00:00, 6 Years ago
;