Node.js 如果我想在不同的方法中添加clearInterval,我应该怎么做?

Node.js 如果我想在不同的方法中添加clearInterval,我应该怎么做?,node.js,vue.js,setinterval,nuxt.js,clearinterval,Node.js,Vue.js,Setinterval,Nuxt.js,Clearinterval,我使用设置间隔的moveMarker方法使我的标记在mapbox中,gl沿着我的路线移动,我使用播放按钮触发此功能。我的问题是,如果我想用clearInterval创建暂停按钮,我应该怎么做 我尝试在moveMarker中创建clearInterval函数,但不起作用 这是我移动标记的功能: moveMarker () { const moveCoordinate = [] const loop = setInterval(() => { if (this.in

我使用设置间隔的moveMarker方法使我的标记在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)
  },
在moveMarker方法上调用clearInterval不会起任何作用。您需要将间隔id保存在stop可以访问的位置

e、 g.内部移动标记:

this.intervalId=循环 然后:

停止{ clearIntervalthis.intervalId }
无需将intervalId添加到数据中,因为您不需要它是被动的。

首先,您应该将intervalId存储在data属性中,以便在stop方法中访问它。然后在stop方法中,只需使用存储的间隔调用clearInterval:


好的,这是工作,谢谢。顺便说一句,当我再次点击按钮,我得到的标记是恢复坐标,但创建另一个标记。你知道如何修复它吗?那么你想重置坐标吗?我想如果单击停止功能,然后单击按钮播放,movemarker仍然工作,而不在其上添加新标记
stop () {
    clearInterval(this.moveMarker)
  },
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)
    },
  },
  ...
}