For executing some methods based on some times, then we should go ahead with setTimeout and setInterval.
setTimeout allows to run a function once after the interval of time.
The syntax:
let timerId = setTimeout(func|code, delay[, arg1, arg2...]) |
func|code - Function or a string of code to execute. Mostly, this will be a function. But some peoples may pass a string of code and its not recommended. The reason I have mentioned in Javascript interview section.
delay - The delay before run, should be mentioned in milliseconds (1000 ms = 1 second).
arg1, arg2… - arguments.
Simple Example:
1 2 3 4 5 | function sayHi(welcomeMsg, user) { alert( welcomeMsg + ', ' + user ); } setTimeout(sayHi, 5000, "Hello", "Raj"); // Hello, Raj |
Explanation:
The sayHi method will be called after 5 seconds. Just compare this example with syntax. Hope you got it.
Note:
Do not pass like sayHi(). You should pass always method name only like sayHi without brackets.
No comments:
Post a Comment