所以我有这个代码来使我的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);,但不知道如何正确使用。
我应该如何去实现这个目标呢?
发布于 2016-07-22 17:23:46
您可以使用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的更多信息。
发布于 2016-07-22 17:29:10
使用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)发布于 2016-07-22 17:25:09
我不知道你试过什么,但像这样试一下
$(window).resize(function() {
setTimeout(function() {
editor.removeInstance('myTextarea');
editor = new nicEditor({ iconsPath: 'nicedit/nicEditorIcons.gif', fullPanel: true }).panelInstance('myTextarea');
}, 1000);
});https://stackoverflow.com/questions/38522758
复制相似问题