This is the fifth day of my participation in Gwen Challenge

Sometimes you don’t want a function to run immediately. You want it to re-execute, or even repeat after a certain interval. JavaScript provides us with two implementations: setTimeout and setInterval. Next, we will understand these two methods.

setTimeout

The setTimeout method runs the given function after stopping. It sets a timer and executes the given function (callback) when time expires.

The syntax for the setTimeout method is as follows:

const timerID = setTimeout(function.delay.arg1.arg2,...).Copy the code
  • functionThe function to be executed after a given delay time.
  • delay(Optional) — The time, in milliseconds, that the timer should wait before executing the function. If not specified, the replacement value 0 is used.
  • arg1, arg2, ... argN(Optional) — Arguments to a given function.

The setTimeout method returns an integer value that identifies the timer that was created. This integer is used to clear the timer.

The sample

function sayHello () {
  console.log('Hello')}setTimeout(sayHello, 2000)
Copy the code

After 2 seconds, “Hello” will be printed on the console.

If the sayHello function takes arguments, we can create:

function sayHello(name) {
  console.log(`Hello, ${name}`)}setTimeout(sayHello, 1000.'UI')
Copy the code

This will print “Hello, UI” after 2 seconds.

Use setTimeout to simulate the setInterval effect

clearTimeout

The clearTimeout method is used to cancel the timer. For example, we might want to cancel the timer before it executes the function. Remember that the setTimeout method returns an ID that is used to cancel the timer.

function sayHello(name) {
  console.log(`Hello, ${name}`)}const timerID = setTimeout(sayHello, 3000.'UI')

clearTimeout(timerID)
Copy the code

In the example above, the timer never runs.

setInterval

The setInterval method is used to schedule the function to be repeated after a period of time. The syntax for this method is as follows:

const timerID = setInterval(function.delay.arg1.arg2,...).Copy the code

In this case, the delay is the amount of time (milliseconds) the timer should delay the continuous execution of the function. The setInterval method also returns the ID used to clear the timer.

The sample

function sayHello(name) {
  console.log(`Hello, ${name}`)}setInterval(sayHello, 3000.'UI')
Copy the code

The code above will repeat printing “Hello UI” to the console after 3 seconds.

Note:

The syntax of setInterval is very similar to setTimeout.

The main differences are:

  • The setTimeout method fires only once after the timer expires.

  • The setInterval method repeats the function unless it is cancelled.

To prevent setInterval from running continuously, we can use the clearInterval method.

clearInterval

The clearInterval method is used to stop the setInterval method. It takes a timer ID as an argument and stops the timer with that ID.

let counter = 0
function sayHello(name) {
  console.log(`Hello, ${name}`)
  counter++

  if (counter === 3) {
    clearInterval(timerID)
  }
}

let timerID = setInterval(sayHello, 3000.'UI')
console.log(1)
Copy the code

The sayHello function is executed only three times.

You might wonder why the if statement is inside the function and not outside it, for example:

let counter = 0
function sayHello(name) {
  console.log(`Hello, ${name}`)
  counter++
}

let timerID = setInterval(sayHello, 3000.'UI')

if (counter === 3) {
  clearInterval(timerID)
}
Copy the code

At this point, we need to understand how JavaScript executes the setInterval and setTimeout methods.

Non-blocking I/O operations

Unlike other languages, JavaScript has a thread that executes the task line by line. This means that one line of code must complete execution before moving on to the next. In other words, the execution of the JavaScript code blocks.

However, some non-blocking I/O operations are handled by the underlying engine. Operations such as AJAX, setTimeout, and setInterval fetching data fall into this category. Therefore, JavaScript does not wait for the function (the callback function) passed to the setTimeout or setInterval methods to finish executing before moving on to the next task or line of code.

In the example above, the timer would not have stopped running if we had written it the second way. This is because after executing the line let timerID = setInterval(sayHello, 3000, ‘UI’), JavaScript immediately moves on to the next code block.

if (counter === 3) {  clearInterval(timerID)}
Copy the code

At this point, the condition is not true, so the timer is never cleared. This is why, in our clearTimeout example, the callback function passed to setTimeout was never fired. Because JavaScript immediately goes to the next line of code.

You can read more about Asynchronous JavaScript here.

conclusion

In this article, we discussed how to use setTimeout and setInterval methods to schedule the execution of functions.

reference

How to use the setTimeout and setInterval Methods in JavaScript Sarah Chima – Front-End Developer