Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
JavaScript Not getting an updated value when using screen.width or screen.availWidth in a function which is called by setInterval

Expected behavior:

  1. setInterval calls getScreenWidth() every 2 sec.
  2. getScreenWidth() gets the current width of the (browser) screen.
  3. Width is logged into console.
  4. We change the screen width, by clicking the 'Restore Down' button (beside Minimize) and then altering using mouse pointer.
  5. We see an update in the console output.

Output:

"1536"

The output is always a constant value. (in my case 1536)

I was trying this code on CodePen, and I've tried:

  1. Resizing the output window. (changing it's width)
  2. Resizing the browser. (changing width and even height)

The HTML:

<div id="demo"></div>

The script:

"use strict";
console.clear();

function getScreenWidth() {
    return screen.availWidth;
    // I've also tried screen.width
}

const demo = document.getElementById("demo");
let count = 0;

const intervalId = setInterval(function () {
    demo.innerHTML = getScreenWidth();
    console.clear();
    console.log(demo.innerHTML);
    console.log(count);
    count++;

    if (count > 30) {
        clearInterval(intervalId);
    }
}, 2000);

Since setInterval is indirectly calling getScreenWidth() every 2 sec, shouldn't screen.width be a fresh value every time?

If I assume that it's a fresh value, then does that mean screen.width doesn't equal the current width of the browser window?

Note: The count variable in the code is just to stop setInterval from running indefinitely in the background.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I have the same screen width :)

Anyway, you don't need setInterval you can change it every time the browser is resized using the window onresize event:

window.onresize = function() {
  screen.width; // 1536 / 1530 etc.
};

You also cannot get the browser width (with screen.width)

But you can easily get it using jQuery's .width() function:

$(window).width();

Here's a working example (using jQuery):

"use strict";
console.clear();

function getScreenWidth() {
  return $(window).width();
}

const demo = document.getElementById("demo");

window.onresize = function() {
  demo.textContent = getScreenWidth();
  console.clear();
  console.log(demo.textContent);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="demo"></div>

Edit: You also cannot resize the browser window with JavaScript. This would be a huge security issue, and you should be glad it's not possible.

about 4 years ago · Juan Pablo Isaza Relatório

0

From MDN:

The Screen interface represents a screen, usually the one on which the current window is being rendered, and is obtained using window.screen.

Thus, the screen object here is represents the device output display, and not the browser window.

Again, from MDN:

The Screen.width read-only property returns the width of the screen in pixels.

Thus, screen.width (or window.screen.width) does not give us the browser window width, but it's rather the screen (device output screen) width, which obvious would not change.

To get the width of the browser window, we need to use Element.clientWidth.

From MDN once again:

The Element.clientWidth property is zero for inline elements and elements with no CSS; otherwise, it's the inner width of an element in pixels. It includes padding but excludes borders, margins, and vertical scrollbars (if present).

When clientWidth is used on the root element (the element), (or on if the document is in quirks mode), the viewport's width (excluding any scrollbar) is returned.

Just changing getScreenWidth() would do:

function getScreenWidth() {
    return document.body.clientWidth;
}

Now the console output changes when the width of the browser window changes.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda