使用 setInterval 和 JavaScript

Using setInterval and JavaScript

我正在使用 Notification API,但我无法使其与 SetInterval() 一起使用,有人可以指出我做错了什么。只要我点击事件,通知只显示一次。这是我的代码:

document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {

    if (!('Notification' in window)) {
        alert('Web Notification is not supported');
        return;
    } else {
        setInterval(Notification.requestPermission(function(permission) {
            var notification = new Notification("Hi there!", {
                body: 'I am here to talk about HTML5 Web Notification API',
                icon: 'icon.png',
                dir: 'auto'
            });
            setTimeout(function() {
                notification.close();
            }, 2000);
        }),5000);

    }
    ;
});
});

我卡在这里了,请稍等。

您需要将有效的回调传递给 setInterval()。相反,您传递的是某种方法的 result。试试这个:

setInterval(function () {
    Notification.requestPermission(function(permission) {
        var notification = new Notification("Hi there!", {
            body: 'I am here to talk about HTML5 Web Notification API',
            icon: 'icon.png',
            dir: 'auto'
        });
        setTimeout(notification.close, 2000);
    })}, 5000);

奖励:看看我是如何简化你的 setTimeout 回调的,只传递 notification.close 方法本身,而不是在匿名函数中调用它。干净多了。

用匿名函数包装你的方法

document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {

    if (!('Notification' in window)) {
        alert('Web Notification is not supported');
        return;
    } else {
        setInterval(function(){Notification.requestPermission(function(permission) {
            var notification = new Notification("Hi there!", {
                body: 'I am here to talk about HTML5 Web Notification API',
                icon: 'icon.png',
                dir: 'auto'
            });
            setTimeout(function() {
                notification.close();
            }, 2000);
        })},5000);

    }
    ;
});
});

我发现了这样的东西:

document.addEventListener('DOMContentLoaded', function() {
document.getElementById('notifyBtn').addEventListener('click', function() {
    if (!('Notification' in window)) {
        alert('Web Notification is not supported');
        return;
    } else {
        setInterval(notify, 5000);
    }
});
function notify() {
    Notification.requestPermission(function(permission) {
            var n = new Notification("Hi there!", {
                body: 'I am here to talk about HTML5 Web Notification API',
                icon: 'icon.png',
                dir: 'auto'
            })
            setTimeout(function(){n.close()}, 2000)
        })

}