droprajoja droprajoja - 4 months ago 19
Javascript Question

Setting execution delay to window resize function

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?

Answer

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.