Using setTimeout in objects with Mootools

Often you wish to use setTimeout to call a function in the objects you are creating with MooTools or perhaps even more often you would like to pass parameters into your set time out calls. Well, the MooTools framework has given us a plethora of tools to do all of this and more. In this post I will discuss how you can pass parameters with setTimeout (Well, not really ‘into’ setTimeout, but a better way to get the same result.) and call your functions, delayed and recurring, from your objects created with the MooTools class function.

Closures and bind()

The first problem we tend to encounter the first time we try to do this is that when our member function gets called by setTimeout we get a bunch of errors that our variables are undefined. This problem is caused by JavaScript’s lack of closures which means that there is not hard binding between the function and the object that it is declared in. If you do a little debugging you will discover that the this operator is pointing at the window object not your object. The reason for that is that setTimeout causes the function to be called by the window object and in JavaScript this points to the calling scope.

Because the issue of closures is a problem in many cases when using JavaScript MooTools came up with a generic solution to the problem called bind. The bind() method is a part of the functions.js, found in the Native collection of MooTools functions. Their docs on bind can be found here. The Bind() member function will allow you to bind the this operator to any object you choose, which often will be the this of the object you define it in, but could be any object in the DOM. You can use bind when you call set time out like setTimeout(this.myfunction.bind(this), 1000) to call functions in your object delayed and have still have the this operator point at what you expect it to. That having been said, MooTools has two other functions to help you with delayed and recurring function calls in a much more efficient manner.

Delayed and Recurring calls

As this is an article about setTimeout, you are most likely unconcerned with what closures are and are just wanting your delayed function or recurring/polling/periodic function to work. If so, this is the section for you! The MooTools library provides two functions for calling functions, either delayed or periodically. They are, not surprisingly, called ‘delay’ and ‘periodical’. You use delay when you want a function to execute in so many seconds or periodical when you want a function to execute every so many seconds. Both of these functions return their timer ID and can be stopped by passing that into the $clear() function.

Delay example:

delay_demo = new Class({

    initialize: function(dateString){

        this.count = 0;

        this.delayTimer = this.updateCount.delay(1000, this);

    },

    updateCount: function(){

        this.count++;

    }

});


periodical example:

periodical_demo = new Class({

    initialize: function(dateString){

        this.count = 0;

        this.startTimer();

    },

    updateCount: function(){

        this.count++;

    },

    stopTimer: function(){

        $clear(this.periodicalTimer);

    },

    startTimer: function(){

        this.periodicalTimer = this.updateCount.periodical(1000, this);

    }

});

Passing Parameters

Another important feature of bind, delay and periodical is that they will allow you to pass parameters or arguments to the functions they call. Passing arguments to a function called with bind, delay or periodical is as easy as adding a second parameter for bind and, in the case of delay and periodical, a third parameter that is an array of parameter values; e.g., myfunction.periodical(1000, this, [ParamVal1, ParamVal2, "strParamVal3"]) or myfunction.bind(this, [ParamVal1, ParamVal2, "strParamVal3"]).

Common Errors Encountered

There are some situations where you might get an error that does not really explain what the problem is. I have run into two when working with these functions. The first is the “too much recursion” error from Firefox or FireBug. This error indicates that you have used the parenthesis in a place you should not have, an example is using myfunction().delay(1000, this) instead of myfunction.delay(1000, this). The other is having a function that calls periodical that calls its self, which will cause an exponential increase in the number of calls to that function until your browser locks up.

periodical lockup example:

periodical_demo = new Class({
    initialize: function(dateString){
        this.count = 0;
        this.startTimer();
    },
    updateCount: function(){
        this.count++;
    },
    stopTimer: function(){
        $clear(this.periodicalTimer);
    },
    startTimer: function(){
        this.periodicalTimer = this.startTimer.periodical(1000, this); 

//Note calling startTimer from inside startTimer with periodical is very bad.
    }
});

MooTools has neatly provided simple ways to accomplish all of the tasks we would normally use setTimeout for.



原文链接: http://blog.csdn.net/vince6799/article/details/7282974

转载于:https://my.oschina.net/chen106106/blog/45778

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The Sliding Window Protocol is a flow control protocol used in computer networks to ensure reliable and efficient data transfer between two nodes. It is implemented using a sliding window, which is a buffer of fixed size that stores the data packets to be transmitted and received. The sliding window protocol is a stop-and-wait protocol, which means that the sender sends a packet and waits for an acknowledgement from the receiver before sending the next packet. The receiver sends an acknowledgement packet to the sender indicating that it has received the packet successfully. The sliding window protocol has two parameters: the window size and the sequence number. The window size represents the number of packets that can be sent without waiting for an acknowledgement. The sequence number is a unique identifier assigned to each packet to ensure that the packets are delivered in the correct order. Here is a sample program in Python that implements the Sliding Window Protocol: ```python import socket import time # Define the window size and sequence number WINDOW_SIZE = 4 SEQ_NUM_SIZE = 4 # Define the packet format PACKET_FORMAT = "!I1024s" # Define the server address and port SERVER_ADDRESS = "localhost" SERVER_PORT = 12345 # Define the data to be sent DATA = "Hello, world!".encode("utf-8") # Create the socket and connect to the server client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((SERVER_ADDRESS, SERVER_PORT)) # Initialize the sequence number and window seq_num = 0 window_start = 0 window_end = WINDOW_SIZE # Send the packets while window_start < len(DATA): # Send the packets in the current window for i in range(window_start, window_end): # Create the packet packet_data = DATA[i:i+1024] packet_seq_num = seq_num.to_bytes(SEQ_NUM_SIZE, byteorder="big") packet = struct.pack(PACKET_FORMAT, packet_seq_num, packet_data) # Send the packet client_socket.send(packet) # Increment the sequence number seq_num += 1 # Wait for the acknowledgements ack_received = False while not ack_received: # Set the timeout client_socket.settimeout(1) # Wait for the acknowledgement try: ack = client_socket.recv(1024) # Check if the acknowledgement is valid if ack: ack_seq_num = int.from_bytes(ack, byteorder="big") if ack_seq_num == window_start: ack_received = True # Update the window window_start += 1 window_end += 1 except socket.timeout: # If the timeout occurs, resend the packets in the current window for i in range(window_start, window_end): packet_data = DATA[i:i+1024] packet_seq_num = (seq_num - WINDOW_SIZE + i).to_bytes(SEQ_NUM_SIZE, byteorder="big") packet = struct.pack(PACKET_FORMAT, packet_seq_num, packet_data) client_socket.send(packet) # Wait for a short period of time before sending the next window time.sleep(0.1) # Close the socket client_socket.close() ``` In this program, the client sends the data in packets of size 1024 bytes and waits for an acknowledgement from the server before sending the next packet. The program uses a sliding window of size 4, which means that the client can send up to 4 packets at a time without waiting for an acknowledgement. The program also implements a timeout mechanism to handle lost packets. If the client does not receive an acknowledgement within 1 second, it resends the packets in the current window. Overall, the Sliding Window Protocol provides reliable and efficient data transfer in computer networks by using a sliding window to control the flow of data between two nodes.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值