JS setTimeout

After a given number of milliseconds, the setTimeout() method calls a function or evaluates an expression.

One second is equal to 1000 milliseconds (ms).

It’s important to note that the function only runs once. Use the setInterval() method if you need to repeat the process.

What is the syntax of the JS setTimeout() method?

The syntax is quite simple. It looks as follows.

setTimeout(function, milliseconds, param1, param2, ...)

Parameter Values explanation

ParameterDescription
functionThe function that will be executed and it is required.
millisecondsThis is time and it is optional.
The number of milliseconds to wait for, before executing the code.
If you omit it then 0 will be used as milliseconds value.
param1, …The additional parameters are optional.
Note: The additional parameters are not supported in IE9 and earlier versions

The setTimeout() method allows you to run code after a specified period of time has passed. The method can be considered as a way to set a timer to run JavaScript code at a certain interval.

The following code, will print “Hello World” to the browser console after 3 seconds.

//Example of JS setTimeout() function


setTimeout(function(){
    console.log("Hello World");
}, 3000);

console.log('Time starts now.');


// Output: after 3 seconds it will print 'Hello World'

The setTimeout() method’s first parameter is a JavaScript function that you want to run.

When passing a function, you can either write it directly or refer to a named function, as shown below:

//Example JS setTimeout() named function


// Named Function
function Hello()
{
  console.log("Hello World");
}

setTimeout(Hello, 3000);



// Call function directly

setTimeout(function(){

  console.log("Hello World");

}, 3000);



//

After that, you can specify the millisecond’s parameter, which specifies how long JavaScript should wait before executing the code.

As you can see we specified 3000 in the above example.

Since one second is equivalent to one thousand milliseconds, you must specify 3000 as the second to wait for three seconds.

If the second parameter is omitted, setTimeout() will execute the passed function immediately without any delay.

//Example without specifying the time


//this method will call the function immediately

setTimeout(function(){

  console.log("Hello World");

});


//

Finally, you can use the setTimeout() method to transfer additional parameters that you can use within the feature, as shown below:

// Example, how to pass additional parameters

// passing name and age here
function person(name, age){
  console.log(`Hello, my name is ${name}`);
  console.log(`I'm ${age} years old.`);
}

//person: name of the callback function
//3000: time in milliseconds
//'jhon', 20: additional parameter for name and age


setTimeout(person, 3000, "jhon", 20);


//

JS setTimeout() and ES6

In ES6 the syntax is simple and easy to remember. The working of this function is similar to those examples mentioned above.

For example we can use the arrow function as follow:

//Example ES arrow function and JS setTimeout() function

setTimeout( () => {
console.log('Hello World');
}, 3000);


// If you want to define a function seperatly
funName = () => {
console.log('Hello World')
}
setTimeout(funName, 1000);

//

As you can see it is easy to use arrow function wit setTimeout() method.

Now we will explain how you can pass additional parameters to the arrow function while calling it from the setTimeout() method.

// Example passing additional parameters to the arrow function (ES6 syntax)


// passing name and age
funName = (name, age) => {
console.log(`My name is ${name}`);
console.log(`I am ${age} years old`);
}
setTimeout(funName, 1000, 'Jhon', 20);

//output: 
//My name is Jhon
// I am 20 years old


//

How to reset time in JS setTimeout() method?

A timer set with the setTimeout() method is cleared with the clearTimeout() method.

The clearTimeout() method can be used to prevent the setTimeout() method from executing the operation.

The clearTimeout() method takes the ID value returned by setTimeout() as a parameter.

clearTimeout(id_of_settimeout)

// Example clearTimeout() method

var funID;

function startFunction() {

   // set time
  funID = setTimeout(function(){

   alert("Hello World"); 

  }, 3000);


function stopFunction() {
   
   // clear time
  clearTimeout(funID);

}

//

The setTimeout() method in JavaScript is a built-in method that lets you set the time for execution of a function.

You must pass the amount of time you need to wait in milliseconds, which means you must pass one thousand milliseconds to wait one second.

To stop a setTimeout() method from running, call the clearTimeout() method and transfer the ID value returned by the setTimeout() method.

Reference

https://www.w3schools.com/jsref/met_win_cleartimeout.asp

https://www.w3schools.com/jsref/met_win_settimeout.asp

Similar Posts