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(); }); });
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.
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.
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.
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.
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
.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With