Reputation: 13
So I have this code for making my nicEdit responsive, basically making it reload on window resize so that it can take on the new dimensions:
$(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');
});
Now I want to set an execution delay of like 0.5sec or 1sec so that my browser doesn't lag when I resize it. It lags because the myTextarea
instance gets removed and reloaded rapidly for every pixel resized, on-the-fly.
I have tried various forms of setTimeout(check, 1000);
on different parts of the code but couldn't figure out how to get it right.
How should I go about accomplishing this?
Upvotes: 1
Views: 1215
Reputation: 1087
You can use setTimeout
& clearTimeout
to reset the timeout everytime the window starts resizing. The code in windowResized()
will be called 500ms after the window stops resizing.
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');
};
Read more about clearTimeout()
here.
Upvotes: 2
Reputation: 3065
Use a debounce method or as mentioned in the previous answers a timeout.
The 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);
};
};
And then use it like :
$(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)
Upvotes: 0
Reputation: 9246
I don't know what you've tried but try it like this
$(window).resize(function() {
setTimeout(function() {
editor.removeInstance('myTextarea');
editor = new nicEditor({ iconsPath: 'nicedit/nicEditorIcons.gif', fullPanel: true }).panelInstance('myTextarea');
}, 1000);
});
Upvotes: -1