add timeout to function in javascript

You can use setTimeout function in JavaScript to add a timeout to a function.

index.tsx
function myFunction() {
  console.log("Hello World!");
}

setTimeout(myFunction, 3000); // function will be executed after 3 seconds
133 chars
6 lines

In the above example, myFunction function will be executed after 3 seconds as we have passed 3000 milliseconds as the second parameter to setTimeout function.

You can also pass any arguments to the function by adding them after the timeout value.

index.tsx
function greet(name) {
  console.log(`Hello ${name}!`);
}

setTimeout(greet, 2000, "John"); // will log "Hello John!" after 2 seconds
134 chars
6 lines

In the above example, we are passing greet function and 2000 milliseconds as the timeout value to setTimeout function. We are also passing "John" as a third parameter which will be passed as an argument to greet function. So, it will log "Hello John!" after 2 seconds.

related categories

gistlibby LogSnag