Thursday 20 March 2014

Add Timer in Javascript & Jquery in asp.net c#

Hi friends, today i am going show you how to set timer in javascript and call events or function when times up!

You can also set dynamic timer just passing the value to hidden field "hdnTimer" or you can set your own fix time.

Here is time value given below:

1200 - 20 minutes
2400 - 40 minutes
3600 - 1 Hours
7200 - 2 Hours
So on..



Timer in javascript
Screen 1
Once timer get over it fire alert.

When timer get over fires alert
Screen 2

JS :

You need to add this jquery file

  • jquery-1.7.2.min.js

     

HTML : 

<div align="center" style="width: 100%; height: auto; font-family: Arial;">
        <div style="width: 960px; height: auto;">
            <div style="background-color: #eee; width: 500px; border: 1px solid #CCC;">
                <h1>
                    Timer in Javascript and Jquery</h1>
                <div>
                    <div style="width: 150px; height: 80px; background-color: #ececec; border: 1px solid #eaeaea;">
                        <div style="padding: 20px 20px 30px 20px; color: #323232; font-family: Arial; font-size: 20px;">
                            <input type="hidden" id="hdnTimer" value="10">
                            Time Left <b id="idTimerLCD"></b>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

 

Script :

 var _timerHandle = setInterval(function() { MyTimer() }, 1000);

        function MyTimer() {
            var valueTimer = $('#hdnTimer').val();

            if (valueTimer > 0) {
                valueTimer = valueTimer - 1;
                //Get Hours Min Secs
                hours = (valueTimer / 3600).toString().split('.')[0];
                mins = ((valueTimer % 3600) / 60).toString().split('.')[0];
                secs = ((valueTimer % 3600) % 60).toString();

                if (hours.length == 1) hours = '0' + hours;
                if (mins.length == 1) mins = '0' + mins;
                if (secs.length == 1) secs = '0' + secs;

                $('#idTimerLCD').text(hours + ':' + mins + ':' + secs);
                $('#hdnTimer').val(valueTimer);
                //Set time as Page title
                document.title = $('#idTimerLCD').text();
            }
            else {
                //Here Timer get over you can call any function here
                clearInterval(_timerHandle);
                alert(" Your time is up ! \n\n Trigger button click or any function you want to execute.");
                //(Add Button name) Button click event comes here
                //$('#btnName').click();

            }
        }

 

Download Link :

Download Complete Project

Enjoyed this post? Share and Leave a comment below, thanks! :)

No comments:

Post a Comment