How to run a Javascript function with certain delay?
I need to invoke a function after couple of seconds, How can I do this in Javascript?
1 Answer
5 years ago by VD
Using setTimeout we can invoke a function with delay. Following code shows you how to do that.
setTimeout(() => your_function(), 1000);
First parameter for setTimeout is a function and the second parameter is time in milliseconds.
Following is a full example that demonstrates setTimeout
function hello()
{
console.log("Hello, World!");
console.log('after:' + new Date());
}
console.log('before:' + new Date());
setTimeout(() => hello(), 1000);
Output:
before:Mon Jul 06 2020 14:32:05 GMT+0000
Hello, World!
after:Mon Jul 06 2020 14:32:06 GMT+0000
You can run this and see yourself here https://onecompiler.com/javascript/3vy55pdma
5 years ago by Karthik Divi