I'm having some trouble trying running a function only once when onresize event is triggered, I have looked at this questions DOM onresize event but I'm not using jQuery and can't get that function to work without. Any suggestions?
Asked
Active
Viewed 6,551 times
2
-
Post some code - from the top of my head, use a boolean? – eric.itzhak Jun 21 '12 at 21:50
-
1The linked answer doesn't need jQuery to work, pure JavaScript do. Read again – Alexander Jun 21 '12 at 21:51
-
$(window).resize($.debounce(1000, function() { // Handle your resize only once total, after a one second calm. ... })); I have tried using this without jquery but it doesn't work, I'm using this inside a firefox extension – ama2 Jun 21 '12 at 21:53
-
you can't use jQuery's namespace (`$`) as in `$(window).resize` if you don't have jQuery, instead you'll have to bind it in the `window.onresize = function() {` (or another listener) and use the `Cowboy` namespace as described in the author's page. I'd personally use a `setTimeout` and `clearTimeout`. – Fabrício Matté Jun 21 '12 at 21:56
2 Answers
11
The resize event is called once for every frame during the resizing operation. If you want to call it when resizing is finished, just set timer with a callback function.
var timeOut = null;
window.onresize = function(){
if (timeOut != null)
clearTimeout(timeOut);
timeOut = setTimeout(function(){
// YOUR RESIZE CODE HERE
}, 500);
};

Arlen Anderson
- 2,486
- 2
- 25
- 36
-
Of course, if the user holds the window size steady for half a second, this method will not quite work as expected. It's a good answer, but not foolproof. – Niet the Dark Absol Jun 21 '12 at 21:58
-
2I don't think that matters. That type of behavior may even be what he's looking for. – Arlen Anderson Jun 21 '12 at 22:01
-
-
1"If you can't solve it with `setTimeout`, you're not using enough `setTimeout`s." – Fabrício Matté Jun 21 '12 at 22:05
4
You could use the debounce
implementation from underscore:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
if (immediate && !timeout) func.apply(context, args);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
window.onresize = debounce(function() {
// Your code here
}, 500);
Or use the library from the linked question. Without jQuery, it is Cowboy.debounce(...)
.

Bergi
- 630,263
- 148
- 957
- 1,375