运行 Javascript 每 X 秒 - 这段代码有什么问题?

Running Javascript every X seconds - what's wrong with this code?

我正在使用此代码来检测设备何时处于横向状态,但它不起作用。有什么想法吗?

 function OrientationAlert {
if(window.innerHeight < window.innerWidth){
    alert("Please rotate your device and view this in portrait orientation.");
   }

   setInterval(OrientationAlert, 5000);
}

尝试

setInterval(function(){ 
   if(window.innerHeight < window.innerWidth){
     alert("Please rotate your device and view this in portrait orientation.");
   } 
}, 3000);

您也可以使用 orientationchange 事件。 这是一个例子:

function doOnOrientationChange() {
    switch(window.orientation)
    {
        case -90:
        case 90:
            alert('landscape');
            break;
        default:
            alert('portrait');
            break;
    }
}

window.addEventListener('orientationchange', doOnOrientationChange);

// Initial execution if needed
doOnOrientationChange();

浏览器支持还不错,因为它只能在移动设备上发挥作用,所以它可能是您的一个选择。这是我可以使用的 Link.

在这里您可以找到有关

的更多信息

Screen Orientation API.

您也可以像这样在回调函数中声明它:

window.addEventListener('orientationchange', function() {
    switch(window.orientation)
    {
        case -90:
        case 90:
            alert('landscape');
            break;
        default:
            alert('portrait');
            break;
    }
});

希望对您有所帮助。

function OrientationAlert(){
if(window.innerWidth < 500){
    setInterval(function(){
    if(window.innerHeight < window.innerWidth){
        alert("Please rotate your device and view this in portrait orientation.");
       }
    }, 5000);
    }
}
    <!DOCTYPE html>
    <html>
    <body onload="OrientationAlert()">
    </body>
    </html>

试试这个!!

更新:- 根据您在评论中提到的要求添加了条件

 if(window.innerWidth < 500) {
//the setInterval() funcion is registered at the time of page or else it wont
    }
var a = OrientationAlert {...}
setInterval(a,5000);