2016-07-22 94 views
0

所以我必須讓我的nicEdit響應,基本上使它重新加載窗口大小調整,以便它可以在新的層面驗證碼:設置執行延遲到窗口大小調整功能

$(function() { 
    editor = new nicEditor({iconsPath : 'nicedit/nicEditorIcons.gif', fullPanel : true}).panelInstance('myTextarea'); 
}) 

$(window).resize(function() { 
    editor.removeInstance('myTextarea'); 
    editor = new nicEditor({iconsPath : 'nicedit/nicEditorIcons.gif', fullPanel : true}).panelInstance('myTextarea'); 
}); 

現在我想成立執行延遲爲0.5秒或1秒,以便在調整它的大小時,我的瀏覽器不會滯後。它滯後,因爲myTextarea實例被刪除並快速重新加載每個像素的大小,即時。

我在代碼的不同部分嘗試過各種形式的setTimeout(check, 1000);,但無法弄清楚如何正確使用它。

我應該如何去做到這一點?

回答

1

您可以使用setTimeout & clearTimeout在每次窗口開始調整大小時重置超時。窗口停止調整大小後,windowResized()中的代碼將被調用500ms。

var windowResizeTimeout = null; 

$(window).resize(function() { 
      // Clears the timeout if it exists 
      if (windowResizeTimeout) clearTimeout(windowResizeTimeout); 
      // Sets a new timeout 
      windowResizeTimeout = setTimeout(windowResized, 500); 
}); 

function windowResized() { 
      // window resized.. 
      editor.removeInstance('myTextarea'); 
      editor = new nicEditor({iconsPath : 'nicedit/nicEditorIcons.gif', fullPanel : true}).panelInstance('myTextarea'); 
}; 

瞭解更多關於clearTimeout()here

0

我不知道你已經嘗試過什麼,但嘗試這樣

$(window).resize(function() { 

    setTimeout(function() { 

     editor.removeInstance('myTextarea'); 
     editor = new nicEditor({ iconsPath: 'nicedit/nicEditorIcons.gif', fullPanel: true }).panelInstance('myTextarea'); 

    }, 1000); 

}); 
+0

這將設置一個新的超時爲每個調整事件多數民衆贊成燃煤導致其重繪多次 –

+0

你說得對。你的答案實際上是正確的實施。 – Aron

0

使用debounce method或如前面的答案中提到的超時。

去抖方法:

/** 
* Execute a function given a delay time 
* 
* @param {type} func 
* @param {type} wait 
* @param {type} immediate 
* @returns {Function} 
*/ 
var debounce = function (func, wait, immediate) { 
    var timeout; 
    return function() { 
     var context = this, args = arguments; 
     var later = function() { 
       timeout = null; 
       if (!immediate) func.apply(context, args); 
     }; 
     var callNow = immediate && !timeout; 
     clearTimeout(timeout); 
     timeout = setTimeout(later, wait); 
     if (callNow) func.apply(context, args); 
    }; 
}; 

,然後用它喜歡:

$(window).resize(debounce(function(){ 
    // the following function will be executed every half second 
    editor.removeInstance('myTextarea'); 
    editor = new nicEditor({iconsPath : 'nicedit/nicEditorIcons.gif', fullPanel : true}).panelInstance('myTextarea'); 
},500)); // Milliseconds in which the task should be executed (500 = half second) 
+0

Aron發佈的簡單setTimeout方法有什麼優勢? – droprajoja

+1

如果觸發另一個事件,它將清除超時,否則最終會在每次調整大小事件後設置並運行多個超時。 –

+0

@droprajoja只是嘗試使用該功能,你會發現自己。反彈清除之前的超時,並會導致您的功能只執行一次。如果你測試Aron提供的代碼,你會看到該函數被多次執行。思南的答案以同樣的方式消除,但是簡化了。 –