将执行延迟设置为窗口大小调整功能

时间:2016-07-22 09:20:39

标签: javascript jquery

所以我有这个代码让我的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);,但无法弄清楚如何正确使用它。

我应该如何完成这项工作?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我不知道你曾经尝试过但尝试过这样的事情

Context context = view.getContext();
context.startActivity(new Intent(context, TicketDetails.class));

答案 2 :(得分: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)