admin管理员组

文章数量:1353636

How can I have my javascript code constantly run? The situation is that I want some page elements to be resized when the page resizes. I'm thinking that the way to do this would be to have some javascript code that constantly runs, and whenever the page size changes, it resizes that element.
I tried doing this with setTimeout() and a really small value, but it didn't seem to work.

How can I have my javascript code constantly run? The situation is that I want some page elements to be resized when the page resizes. I'm thinking that the way to do this would be to have some javascript code that constantly runs, and whenever the page size changes, it resizes that element.
I tried doing this with setTimeout() and a really small value, but it didn't seem to work.

Share Improve this question asked Feb 7, 2010 at 1:29 chustarchustar 12.5k26 gold badges84 silver badges119 bronze badges 1
  • 2 Just a reminder: Javascript in the browser is single-threaded, and runs in the same thread as the rendering engine, and usually the same one as the rest of the gui. – Anonymous Commented Feb 7, 2010 at 1:34
Add a ment  | 

3 Answers 3

Reset to default 6

JavaScript is an Event based language, that is you add event listeners to things and then a function is called when that event occurs. This saves you from having a loop run continuously to to check the state of an item.

The window supports onResize in JavaScript, so for example:

window.addEventListener("resize", function(event){
  alert("you just resized the window. If you inspect the event variable you will find some usefull details");
}, false);

http://www.quirksmode/dom/events/index.html#t020

You should hook your script to the resize event

I would look at a framework like jquery where you can register a function with a page event.

$('body').resize(function() { ... });

By running the javascript all the time, you run the risk of really bogging down a cpu (especially on single core systems) and really slowing down the browser.

本文标签: htmlConstantly running javascriptStack Overflow