js 节流函数 2

js 节流函数的核心思想:

防止频繁的执行,

最后的操作(的影响)覆盖掉之前的操作(的影响).

实现方式:延迟执行(有点像"推迟满足感")

这种实现方式让我想到了之前我做的swing窗口空闲多久就自动关闭的功能

具体思路:

(1)swing不是当前窗口时,开始启动定时器,

protected void windowDeactivated2(GenericFrame frame){
		if (isLocked) {// over three times and is still locked,meanwhile use
			// try to log in
			if (task != null) {
//				System.out.println("取消任务");
				task.cancel();
				task = null;
			}
		} else {// first into this if clause(if (timesFail >=
				// LoginUtil.MAX_LOGIN_FAIL_TIMES ))
			task = null;
		}
		if (timer == null) {
			timer = new Timer();
		}
	
		if (task == null) {
			task = new MyTask(frame);
		}
		timer.schedule(task, MILLISECONDS_WAIT_WHEN_BLUR*1000);
//		System.out.println("开始计时(second):"+TimeHWUtil.formatDateZhAll(TimeHWUtil.getCurrentTimestamp()));
//		System.out.println("定时时间(second):"+MILLISECONDS_WAIT_WHEN_BLUR);
		isLocked = true;
	}

public void windowDeactivated(WindowEvent e) {

setActived22(false);

//System.out.println("window Deactivated");

if(isTiming){

windowDeactivated2(frame);

}

super.windowDeactivated(e);

}

 

(2)在定时器等待的过程中,如果激活了swing窗口,那么取消定时器,

public void windowActivated(WindowEvent e) {
				setActived22(true);
				System.out.println("window Activated");
				if (task != null) {
//					System.out.println("取消任务");
					task.cancel();
					task = null;
				}
				GenericFrame.this.setTiming(true);//恢复,不然后面就不会定时了.
				
				super.windowActivated(e);
			}

 (3)如果不是当前窗口,则先取消定时器,再执行(1),即重新定时.

说明:swing窗口是当前窗口时,执行windowActivated 方法

参考:http://hw1287789687.iteye.com/blog/2311976

猜你喜欢

转载自hw1287789687.iteye.com/blog/2312189