JavaScript implements a timer plugin that binds the DOM

Source: Internet
Author: User
Tags setinterval

Problem

Using native settimeout and setinterval can only be implemented, timed to execute event handlers,

In web development, there is often a situation where timers are used to periodically update data in a page area,

Often after the page is loaded, the timer is started, and then the timers are executed at intervals.

Periodically refreshed areas on the page may disappear dynamically, especially if Ajax is widely used today,

If the area of the timed refresh is removed, the timing equipment also needs to be automatically cleared off.

This two interface, if it is necessary to implement this effect, self-maintenance timer handle, and in processing Timer event function,

First, determine if the specified refresh area is still present? If it still exists, the logic for data refresh continues.

If it does not exist, the timer is removed and the data refresh action is not performed.

Scheme

Such timers need to be bound to the target DOM, and in the event handler, the timer is cleared if the DOM is deleted.

Code

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>my First webcomponent</title>
<body>
<input type= "text" id= "test" name= "test" value= "test" ></input>
<input type= "button" id= "Removetest" name= "Removetest" value= "Removetest" ></input>
<script type= "Text/javascript" >
/************************ Timer Timer plugin start **********************/
(function () {
/* This function lets the timer handle the handler,
You can get to the object that called Settimeout_context_binding */
var settimeout_context_binding = function (Vcallback, ndelay/*, ARGUMENTTOPASS1, ARGUMENTTOPASS2, etc. */) {
var othis = this, Aargs = Array.prototype.slice.call (arguments, 2);
Return window.settimeout (vcallback instanceof function function () {
Vcallback.apply (Othis, Aargs);
}: Vcallback, Ndelay);
};

       /* This function lets the timer handle handler,
             can get to the object called Settimeout_context_binding */
        var setinterval_context_binding = function (Vcallback, ndelay/*, ARGUMENTTOPASS1, ARGUMENTTOPASS2, etc. */) {
 & nbsp;          var othis = this, Aargs = Array.prototype.slice.call ( arguments, 2);
            return Window.setinterval (vcallback instanceof Function? function () {
                Vcallback.apply (Othis, Aargs);
           }: Vcallback, Ndelay);
       };

       /* Define the constructor of the timer */
        var Timer = function (fnalarm, options)
        {
            /* External settable */
             This.fnalarm_inner = function () {
                 $ ("#timer_msg"). Printmsg (this.timerHandle.toString ()
                     + "- Please add custom Fnalarm ")
           };

This.timeout = undefined;
This.interval = undefined;
This.contextdom = undefined;

/* Inner Maintain variable */
This.timerhandle;

/* Set external variable */
if (fnalarm)
{
This.fnalarm_inner = Fnalarm;
}

            if (options)
             {
                 if (options.timeout)
                 {
                     this.timeout = options.timeout;
               }

                if ( Options.interval)
                 {
                     this.interval = Options.interval;
               }

if (options.contextdom)
{
This.contextdom = Options.contextdom;
}
}
}

/* Define the Timer's prototype method */
Timer.prototype.start = function () {
var context_binding_timer = undefined;
var time_value = undefined;

if (this.timeout) {
Context_binding_timer = settimeout_context_binding;
Time_value = This.timeout;
} else {
Context_binding_timer = setinterval_context_binding;
Time_value = This.interval;
}

This.timerhandle = Context_binding_timer.call (this, function () {
/* The purpose of the context Dom binding is here:
If the DOM bound by this timer has been removed from the document, the timed processing is not called handler */
if (This.contextdom &&!document.body.contains (this.contextdom))
{
This.stop ();
Return
}

This.fnAlarm_inner.call (this);
Delete This.timerhandle;
}, Time_value);
};

Timer.prototype.stop = function () {
if (this.timeout) {
Cleartimeout (This.timerhandle)
} else {
Clearinterval (This.timerhandle)
}
Delete This.timerhandle;
};

Timer.prototype.getTimerID = function () {
return this.timerhandle;
};

/* Open Interface */
Window. Contextbindingtimer = timer;
})();
/************************ Timer Timer plug-in end **********************/

Bind Remove Button Event
document.getElementById ("Removetest"). Onclick=function () {
var test = document.getElementById ("test");
Test.parentNode.removeChild (test);
}

var targetdom = document.getElementById ("test");

/* Construct a interval timer with setTimeout timer */
var timer = new Contextbindingtimer (function () {
Console.log ("Access once!")
}, {timeout:1000, contextdom:targetdom})

Timer.start ()
</script>
</body>

Implementation effect

The number of timer prints continues to increase before the input box is deleted on the page.

After clicking the button to delete the input box, the timer print data has not changed, proving that the timer has been deleted.

JavaScript implements a timer plugin that binds the DOM

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.