加速窗口调整功能性能 [英] Speeding up window resize function performance

查看:62
本文介绍了加速窗口调整功能性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类似于以下内容的脚本:

I have some script similar to the following:

var breakpoints = [0,240,480,960,9999],
    bpCount = breakpoints.length,
    windowsize = 0;

window.onresize = function() {

    windowsize = document.body.clientWidth;

    for(var i=0; i<bpCount; i++) {
        if(windowsize >= breakpoints[i] && windowsize < breakpoints[i+1]) {
            doSomething(breakpoints[i]);
            break;
        }
    }    

};

然而,这似乎运行得相当慢,即使在一台不错的PC上的Chrome中,甚至在'doSomething '只是执行'console.log',所以我只是想知道在调整大小时是否有更好的方法来检查屏幕尺寸是否介于两个值之间?

However this seems to run pretty slowly, even in Chrome on a decent PC, and even when 'doSomething' is just performing a 'console.log', so I was just wondering if there was any better way of checking whether the screen size is between two values as it resizes?

谢谢

推荐答案

不要每次轮询的大小。你正在使用过多的计算能力。

Don't poll for the size every single time. You're using way too much computing power.

相反,制作一个计时器并经常检查大小( 10 ms 可能太快了):

Instead, make a timer and check for the size every so often (10 ms might be too fast):

var checkWindowSizeTimer;

function checkWindowSize() {
    var windowsize = document.body.clientWidth;

    if (windowsize >= breakpoints[i] && windowsize < breakpoints[i+1]) {
        doSomething(breakpoints[i]);
        clearInterval(checkWindowSizeTimer);
    }
}

window.onresize = function() {
  checkWindowSizeTimer = setInterval(checkWindowSize, 10);
}

当窗口调整大小超过边界时,计时器退出。

When the window is resized past your bounds, the timer exits.

这篇关于加速窗口调整功能性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆