setTimeout(), clearTimeout(), setInterval() and clearInterval() : Everything you need to know

Β·

3 min read

Let us understand these methods in the similar order as given in title.

1. setTimeout() method:

This method allow us to run a function (or execute a piece of code) once the given interval of time expires.

Here is the syntax:

let timeoutID = setTimeout(functionName, time in milliseconds, arguments(if any))

timeoutID is the value returned by the setTimeout. Although, we can name it anything.

Let's see an example:

function greet(){
     console.log("Welcome to my blog")
  }

setTimeout(greet, 5000)

Output:

1.PNG

It will print "Welcome to my blog". But it will take 5 seconds (5000 milliseconds) to do so (after the code is being run).

Let's see another example with a function which has parameters:

function greet(name){
     console.log("Welcome to my blog " + name)
  }

setTimeout(greet, 5000, "Elon")

Output:

2.PNG

2. clearTimeout() method:

This method prevents the function which we gave in setTimeout from executing. In other words it clears the function given in setTimeout before the timer expires.

Let us understand it with an analogy: Let's say a person came to your blog and you want him to signup. So, you set a timer for 20 seconds (using setTimeout) thinking that the signup option will automatically pop up after 20 seconds. Now, here comes the fun part: What if the the person has already signed up within those 20 seconds. In this case we will give an if-else block and if the person has already signed up in 20 seconds, we'll execute clearTimeout otherwise we won't.

Let's see another example πŸ‘‡: On execution of the below code "Good Morning" will be printed after 5 seconds. However, nothing will be printed if we uncomment the stopFunction().

const timeoutID = setTimeout(myGreeting, 5000);

function myGreeting() {
  console.log("Good Morning")
}

function stopFunction() {
  clearTimeout(timeoutID);
}

//stopFunction()

3. setInterval() method:

This method allows us to run a function repeatedly. The time interval between each repetition is provided by the setInterval.

Here is the syntax:

setInterval(functionName, interval in milliseconds, arguments(if any))

Let's see the below example: After every 1 second "Welcome to my blog" will be printed.πŸ‘‡

function greet(){
     console.log("Welcome to my blog")
  }

setInterval(greet, 1000)

output:

1.gif

Now, let's make an awesome clock using what we have learned till now:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div Id="clock"></div>
    <script>
        function time(){
            let currentTime = new Date;
            document.getElementById("clock").innerHTML = currentTime;
        }
        setInterval(time, 1000);
    </script>
</body>
</html>

2.gif

So simple (yet awesome!)

4. clearInterval() method

Let's see what MDN has to say: The global clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval().

It is similar to clearTimeout (which is used to clear setTimeout)

Let's see it in action:

Example 1:

function greet(){
     console.log("Welcome to my blog")
  }

const intervalID = setInterval(greet, 1000)
clearTimeout(intervalID)

The above ☝️ code will not print anything.

Example 2: Write a function that takes a number. Then print a countdown from that number to 0. At zero print "Bang Bang!":

for example if the function takes 6, it should print thisπŸ‘‡:

gif1.gif

let countDown = num => {intervalID = setInterval(() => 
{num = num - 1
if(num === 0){
console.log("BangBang")}
else if(num === -1){
clearInterval(intervalID)}
else{
console.log(num)}}, 1000)}

countDown(6)

Since currently I am practicing ES6+, I wrote the above code in arrow functions. If you want me to write it in terms of normal functions just leave a comment and I'll be happy to do it.

I hope you liked the article. I loved it!

I write articles related to web development. Follow me here if you are learning the same.

If you love the article follow me on Twitter: @therajatg

If you are the Linkedin type, let's connect: linkedin.com/in/therajatg

Have an awesome day ahead πŸ˜€!

Β