2009年6月24日 星期三

Javascript的延遲執行

Delaying Javascript Event Execution
If you're looking to execute javascript code whenever someone finishes (or stops temporary) scrolling, moving the mouse, or resizing the page, you may find the following code segment useful.
作者舉了幾個事件onScroll, onMouseMove, onResize,這些事件會被頻繁觸發。出於執行性能考慮,有些回調最好安排在事件結束之後,這時候就可以通過延時執行Javascript的方法實現,模擬onScrollEnd, onMouseMoveEnd和onResizeEnd。

 var onFooEndFunc = function() {
var delay = 50; /* milliseconds - vary as desired */
var executionTimer;
return function() {
if (executionTimer) {
clearTimeout(executionTimer);
}
executionTimer = setTimeout(function() {
// YOUR CODE HERE
}, delay);
};
}();

網誌存檔