3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

windowのイベントリスナをすぐにremoveするとcallbackが起きない

Posted at

何も起きない例

window.addEventListener("hashchange", foo)
location.hash = "a"
window.removeEventListener("hashchange", foo)

window.addEventListener("scroll", foo)
scrollTo(100, 100)
window.removeEventListener("scroll", foo)

function foo(e){
  console.log(e.type)
}

*実際にハッシュもつくし、スクロールもする。

対応

removeを以下で行う

  • callback内でする
  • setTimeoutで遅らせる
function foo(e){
  console.log(e.type)
  window.removeEventListener(e.type, foo)
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?