if (window.DeviceMotionEvent) { window.addEventListener("devicemotion", motionHandler, false); } else { document.body.innerHTML = "What user agent u r using???"; } 很多时候要等很久才触发事件。所以很影响页面加载。如何给 eventlistener 设置个 timer,在一定时间内如果不触发时间就输出默认值?
1
geelaw 2017-05-09 17:54:14 +08:00
你可以用一个值手动触发这个 handler 让页面正常加载。
|
2
geelaw 2017-05-09 18:00:02 +08:00
当然如果你执意要判断事件的发生,可以用 setTimeout。
(function () { var happened = false; var happenedHandler = function() { happened = true; }; var detectIfHappenedHandler = function () { if (!happened) alert('The event has not happened since it was registered.'); }); window.addEventListener('yourEvent', happenedHandler, false); window.setTimeout(detectIfHappenedHandler, 1000) })(); |
3
geelaw 2017-05-09 18:02:13 +08:00
@geelaw 更正:
(function () { var happened = false; var happenedHandler = function() { window.removeEventListener('yourEvent', happenedHandler, false); happened = true; }; var detectIfHappenedHandler = function () { if (!happened) alert('The event has not happened since it was registered.'); }; window.addEventListener('yourEvent', happenedHandler, false); window.setTimeout(detectIfHappenedHandler, 1000) })(); |
4
wico97 OP @geelaw 不过这样也不能判断在一定时间内捕捉到 event 呀。最好想在页面加载的时候就判断是否捕捉到事件,否则输出默认值。
|
5
geelaw 2017-05-09 20:03:19 +08:00
@wico97 不明白你在说什么。如果上面那段代码执行之后 1 秒后没有发生 yourEvent,那么 detectIfHappenedHandler 就会运行。
如果你想知道 yourEvent 到底会不会发生,你只能问问浏览器支不支持,如果浏览器的实现是坏掉的,那你是无能为力的。 |
6
Lxxyx 2017-05-09 21:10:48 +08:00
throttle 和 debounce,可以看看 loadsh 里的实现
|