Showing posts with label Advanced-SetTimeout. Show all posts
Showing posts with label Advanced-SetTimeout. Show all posts

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.





setTimeout with clearTimeout

We can use “timer identifier” which will be returned by setTimeout and the same we can use to cancel the execution.

Syntax:



let timerId = setTimeout(...);
clearTimeout(timerId);

Example:



1
2
3
let myVar = setTimeout(function(){ alert("Hello"); }, 3000);

let xxx = clearTimeout(myVar);

Explanation:

1. Line number 1 will be executed initially

2. To display the alert Hello message 3 seconds need to be waited.

3. But line number 3 will be executed before three seconds. So alert message will not be displayed here.

setTimeout


For executing some methods based on some times, then we should go ahead with setTimeout and  setInterval.

setTimeout allows to run a function once after the interval of time.


The syntax:



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


func|code -  Function or a string of code to execute. Mostly, this will be a function. But some peoples may pass a string of code and its not recommended. The reason I have mentioned in Javascript interview section.

delay -  The delay before run, should be mentioned in milliseconds (1000 ms = 1 second).

arg1, arg2…  - arguments.

Simple Example:



1
2
3
4
5
function sayHi(welcomeMsg, user) {
  alert( welcomeMsg + ', ' + user );
}

setTimeout(sayHi, 5000, "Hello", "Raj"); // Hello, Raj

Explanation:

The sayHi method will be called after 5 seconds. Just compare this example with syntax. Hope you got it.

Note:

Do not pass like sayHi(). You should pass always method name only like sayHi without brackets.