Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout delay doesn't wait for the timeout

Tags:

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(); });  }); 
like image 876
timkl Avatar asked Nov 19 '11 18:11

timkl


People also ask

Does setTimeout execute immediately?

Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.

Is setTimeout guaranteed?

setTimeout is a guarantee to a minimum time of execution. I wrote two gists that you can copy and paste into the console to check this.

How do you wait for setTimeout?

Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.

What is delay () in JavaScript?

Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.


2 Answers

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.

like image 90
James Allardice Avatar answered Sep 21 '22 19:09

James Allardice


You need to wrap your statements in anonymous functions and also stagger your timings -

setTimeout(function(){writeNumber.html("1")},1000); setTimeout(function(){writeNumber.html("2")},2000); setTimeout(function(){writeNumber.html("3")},3000); 

If you set everything to 1000 the steps will pretty much run simultaneously as the setTimeout function will run the task 1 second after you called the function not 1 second after the previous call to the setTimeout function finished.

Demo - http://jsfiddle.net/JSe3H/1/

like image 28
ipr101 Avatar answered Sep 20 '22 19:09

ipr101