Monday, April 30, 2018

setInterval

It runs the function regularly after the given interval of time. Suppose, If you want to stop the actions you should call clearInterval(timerId).

The setInterval method syntax is same as setTimeout.

Syntax:


let timerId = setInterval(func|code, delay[, arg1, arg2...])

Example:



let timerId = setInterval(() => alert('I will run every 3 seconds continuously'), 3000);

The above alert will show up every 3 seconds once.

setInterval with clearInterval

Example:

1
2
3
4
let timerId = setInterval(() => alert('Test'), 2000);

// after 5 seconds stop the interval
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);

Explanation:
       
                1. Line number 1 will be run continuously for every 2 seconds.

                2. But line number 5 will clear the interval time after 5 seconds. So after 5 seconds alert 
                    "Test" will not shown.





No comments:

Post a Comment