【问题标题】:What should I do if I want to add clearInterval in diferent methods?如果我想在不同的方法中添加 clearInterval 怎么办?
【发布时间】:2019-12-19 16:18:32
【问题描述】:

我有moveMarkersetInterval 的方法来使我在mapbox-gl 中的标记沿着我的路线线移动,并且我已经播放按钮来触发这个功能。我的问题是,如果我想用 clearInterval 创建暂停按钮该怎么办?

我尝试在moveMarker 中创建clearInterval 的函数,但不起作用

这是我移动标记的功能:

moveMarker () {
    const moveCoordinate = []
    const loop = setInterval(() => {
      if (this.index + 1 === (this.coordinates.length - 1)) {
        clearInterval(loop)
      }
      for (let index = 0; index < moveCoordinate.length; index++) {
        moveCoordinate[index].remove()
      }
      this.map.panTo(this.coordinates[this.index])
      const lat = this.coordinates[this.index][0]
      const lng = this.coordinates[this.index][1]
      const newMarker = new mapboxgl.LngLat(lat, lng)
      console.log('new', newMarker)
      const markerMapbox = new mapboxgl.Marker()
        .setLngLat(newMarker)
        .addTo(this.map)
      moveCoordinate.push(markerMapbox)
      this.index++
    }, 1000)
  },

这是停止功能:

stop () {
    clearInterval(this.moveMarker)
  },

【问题讨论】:

    标签: node.js vue.js setinterval nuxt.js clearinterval


    【解决方案1】:

    首先,您应该将区间存储在数据属性中,以便在stop 方法中访问它。然后在stop 方法中调用clearInterval 并存储interval:

    export default {
      ...
      data() {
        return {
          interval: null
        }
      },
      methods: {
        moveMarker () {
          const moveCoordinate = []
          this.interval = setInterval(() => {
            if (this.index + 1 === (this.coordinates.length - 1)) {
              clearInterval(this.interval)
            }
            for (let index = 0; index < moveCoordinate.length; index++) {
              moveCoordinate[index].remove()
            }
            this.map.panTo(this.coordinates[this.index])
            const lat = this.coordinates[this.index][0]
            const lng = this.coordinates[this.index][1]
            const newMarker = new mapboxgl.LngLat(lat, lng)
            console.log('new', newMarker)
            const markerMapbox = new mapboxgl.Marker()
              .setLngLat(newMarker)
              .addTo(this.map)
            moveCoordinate.push(markerMapbox)
            this.index++
          }, 1000)
        },
        stop() {
          clearInterval(this.interval)
        },
      },
      ...
    }
    

    【讨论】:

    • 好的,这工作,谢谢。顺便说一句,当我再次单击按钮时,我有标记是恢复坐标但创建另一个标记。你知道怎么解决吗?
    • 所以你想重置坐标?
    • 我想如果点击停止功能,然后点击按钮播放,movemarker 仍然可以工作,而无需在其上添加新标记
    【解决方案2】:

    moveMarker 方法上调用clearInterval 不会做任何事情。您需要将间隔 id 保存在 stop 可以访问的位置。

    例如里面moveMarker

    this.intervalId = loop
    

    然后:

    stop () {
       clearInterval(this.intervalId)
    }
    

    无需将intervalId 添加到您的data,因为您不需要它是被动的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多