SetTimeout and callback function

vahid_jani
1 min readJun 18, 2022

1-. Why the “setTimeout” function ? we use it to run a function at some point in the future. As the first parameter it gets a callback function but remember we do not call the function here (if we do that it will run it immediately and we dont want that), So just give the name of the function we want to run. as the second argument it receives the future time in milliseconds. lets see an example:

console.log('running line 1');function alertFunc(order) {console.log(`your ${order} is ready`);}setTimeout(alertFunc, 3000, "pizza");console.log('running line 3');

What is the output:

running line 1running line 3your order is ready

The first line is executed. the SetTimeout is pushed to the background trid and the last line is executed. After setTimeout has reached its time, the callback function is executed and “ your order is ready” has been printed out.

2. how to add parameters to setTimeout ?

you can add it after the second parameter (time) like below:

function alertFunc(order) {console.log(`your ${order} is ready`);}setTimeout(alertFunc, 3000, “pizza”);

3. setTimeout will only run once. I you want it to run over and over again use setInterval.

--

--