Home >Web Front-end >JS Tutorial >Master timer functions and delayed execution in JavaScript
To master the timer function and delayed execution in JavaScript, you need specific code examples
In JavaScript, we often encounter the need to execute certain codes regularly. Condition. At this time, you need to use timer functions and delayed execution techniques to complete the task.
JavaScript provides two timer functions: setInterval() and setTimeout(). The setInterval() function can repeatedly execute a piece of code at a specified time interval, while the setTimeout() function executes a piece of code after a specified time.
The following are specific examples of using these two functions:
function sayHello() { console.log("Hello World!"); } setInterval(sayHello, 1000);
In the above code, we define a function named sayHello() for Output "Hello World!". Then use the setInterval() function, pass in the sayHello function as a parameter, and specify the time interval as 1000 milliseconds (i.e. 1 second). In this way, the sayHello function will be executed every 1 second.
function sayHello() { console.log("Hello World!"); } setTimeout(sayHello, 3000);
In the above code, we also define a function named sayHello() for Output "Hello World!". Then pass the sayHello function as a parameter through the setTimeout() function, and specify the delay time as 3000 milliseconds (ie 3 seconds). In this way, after 3 seconds, the sayHello function will be executed.
In addition to directly passing in functions as parameters, we can also use anonymous functions to pass code blocks. The following is an example of using an anonymous function:
setTimeout(function() { console.log("Hello World!"); }, 3000);
In the above code, we use an anonymous function as a parameter of the setTimeout() function. There is only one line of code inside this anonymous function, which is used to output "Hello World!". Likewise, this anonymous function will be executed after 3 seconds.
Summary
The timer functions setInterval() and setTimeout() are widely used in JavaScript and can help us realize the need to execute code regularly. By learning and mastering their use, we can better cope with the needs of various scheduled tasks and use them flexibly in conjunction with specific business scenarios.
The above is the detailed content of Master timer functions and delayed execution in JavaScript. For more information, please follow other related articles on the PHP Chinese website!