In this tutorial, you will learn

  • Timing Functions
  • What are Cookies
javascript timing event and cookie

Javascript Timing Events

Window object provides following two methods to execute a block of code at a specific time interval. 


Javascript SetTimeout 

setTimeout(function, timeInMilliseconds)

JS settimeout method waits for the time and then execute the function only once. In below example, we set time to 5 second. After 5 second wait, the first parameter function will be executed.

var timeout = setTimeout(() => {
    console.log('Timeout')
},5000)


Javascript ClearTimeout

clearTimeout Method

To stop execution before timeout, call clearTimeout method and pass return value of setTimeout method to it.

clearTimeout(timeout)


Javascript SetInterval

setInterval(function, intervalInMilliseconds)

JS setInterval method executes the function after every interval given in millisecond. In below example, after every 2 seconds, function is executed repeatedly. 

var interval = setInterval(() => {
    console.log('Interval')
},2000)

ClearInterval javascript

clearInterval Method

Call clearInterval method by passing return value of setInterval method to stop its execution.

clearInterval(interval)


What is Cookie

What does cookies mean and what do cookies do?

Cookies are used to stored small data on the user’s machine in the form of key value pairs. User can view and delete cookies from browser or can disable cookies to store. Cookies are sent to server with http request so that server can identify this client.

Using javascript methods, you can create, view, change or delete cookies.
You can create cookie with javascript cookie property. Set cookie expiry date and time.

Javascript Create Cookie

You can create new cookie as in below example, we create cookie name with value John and set its expiry date and time.

document.cookie = 'name:John; expires:Friday, 30 October 2020 07:00:10 UTC'


Change Cookie

Cookie value or expiry date and time can be changed as below

document.cookie = 'name:Smith; expires:Sunday, 01 March 2021 23:59:59 UTC'


Delete Cookie

To clear cookies, just change its expiry date to any past date. In below example we delete the cookie name by setting its expiry date to 2019.

document.cookie = 'name:Smith; expires:Sunday, 01 March 2019 23:59:59 UTC'


Post a Comment

Previous Post Next Post