How to create a timer effect with JavaScript

Do you own a website and want your visitors to get redirected to any link after a few seconds and not immediately. Then this tutorial is for you. We will make a page which will function just like Adf.ly website.
When the webpage will open, it will say the visitor to wait for 10 seconds and after 10 seconds the message will appear or the user will be redirected. So let’s program this but before that take a look at what we are going to create.

timer_01

timer_02
Now let’s take a look at the code of this Timer Application.
timer_03

First of all, we will create a div or span inside our body element. Our timer will be shown inside this div. In the next line, we will call the function which we will create in our next step. Here, we will pass two arguments. The time argument, and the div argument. The first field will contain the time, which you want your visitor to wait for. It could be 5 seconds, 10 seconds, 30 seconds etc. Then next will be the ID of the place where we want our timer to show up.
Now comes the Main JavaScript part. First we will create a function, put 2 default values for arguments, which we can change in the body section. Inside the function, we will create a variable. This variable will help us to easily display the time in the specified div. Now we will give a default and static value to the field where the time will be displayed. Except the time value, which is dynamic. It changes every second.
Now we don’t want that the time should display only 10 seconds and does not move the timer. To do that, we need to create a timeout. Now, we will pass the if argument. If the timer is less than 1 second, that is 0 second, then show the final output and also clear the timeout. Like, “Please wait, redirecting you.” Or “Click here to download”. And then after closing that, we will put 2 negative signs after our time variable.
This will reverse count our time variable. Like, 10…9…8…7…6 and if you will add plus sign instead of minus sign then it will increase numbers like, 10….11….12…13….
Now we will set the timeout for 1000 milli seconds that is 1 second. This will refresh the time after every second and update the timer.
We have successfully created a timer that let your visitors see some content only when the countdown is over.
SHARE

Anonymous

Hi. I’m the Author of this blog. I’m A student. I’m I'm learning Programming, Web Designer, Web Developer,I’m a new user of blogger. Inspired to make things looks better.Help me to Make my Blog better for you

  • Image
  • Facebook
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment