You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Timers module in Node.js contains functions that execute code after a set period of time. Timers do not need to be imported via require(), since all the methods are available globally to emulate the browser JavaScript API.
1049
+
1050
+
Some of the functions provided in this module are
1051
+
1052
+
**1. setTimeout():**
1053
+
1054
+
This function schedules code execution after the assigned amount of time ( in milliseconds ). Only after the timeout has occurred, the code will be executed. This method returns an ID that can be used in **clearTimeout()** method.
1055
+
1056
+
**Syntax:**
1057
+
1058
+
```js
1059
+
setTimeout(callback, delay, args )
1060
+
```
1061
+
1062
+
**Example:**
1063
+
1064
+
```js
1065
+
functionprintMessage(arg) {
1066
+
console.log(`${arg}`);
1067
+
}
1068
+
1069
+
setTimeout(printMessage, 1000, 'Display this Message after 1 seconds!');
1070
+
```
1071
+
1072
+
**2. setImmediate():**
1073
+
1074
+
The setImmediate() method executes the code at the end of the current event loop cycle. The function passed in the setImmediate() argument is a function that will be executed in the next iteration of the event loop.
1075
+
1076
+
**Syntax:**
1077
+
1078
+
```js
1079
+
setImmediate(callback, args)
1080
+
```
1081
+
1082
+
**Example:**
1083
+
1084
+
```js
1085
+
// Setting timeout for the function
1086
+
setTimeout(function () {
1087
+
console.log('setTimeout() function running...');
1088
+
}, 500);
1089
+
1090
+
// Running this function immediately before any other
1091
+
setImmediate(function () {
1092
+
console.log('setImmediate() function running...');
1093
+
});
1094
+
1095
+
// Directly printing the statement
1096
+
console.log('Normal statement in the event loop');
1097
+
1098
+
// Output
1099
+
// Normal statement in the event loop
1100
+
// setImmediate() function running...
1101
+
// setTimeout() function running...
1102
+
```
1103
+
1104
+
**3. setInterval():**
1105
+
1106
+
The setInterval() method executes the code after the specified interval. The function is executed multiple times after the interval has passed. The function will keep on calling until the process is stopped externally or using code after specified time period. The clearInterval() method can be used to prevent the function from running.
1107
+
1108
+
**Syntax:**
1109
+
1110
+
```js
1111
+
setInterval(callback, delay, args)
1112
+
```
1113
+
1114
+
**Example:**
1115
+
1116
+
```js
1117
+
setInterval(function() {
1118
+
console.log('Display this Message intervals of 1 seconds!');
1119
+
}, 1000);
1120
+
```
1049
1121
1050
1122
<divalign="right">
1051
1123
<b><a href="#table-of-contents">↥ back to top</a></b>
0 commit comments