我正在使用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);
}
;
});
});
我真的被困在这里,请停下来。
答案 0 :(得分:4)
您需要将有效回调传递给setInterval()
。相反,您正在传递某种方法的结果。试试这个:
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);
Bonus:通过传递setTimeout
方法本身,而不是在匿名函数中调用它,看看我如何简化notification.close
回调。更干净。
答案 1 :(得分:0)
将您的方法包装在匿名函数中
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);
}
;
});
});
答案 2 :(得分:0)
我发现了这样的事情:
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)
})
}