How to stop repeating of variables of "setInterval" Javascript

Viewed 200

I'm a beginner at JS , Now am programming a javascript app

in the app there is a button when the user clicks on it, a door supposed to be opened for 10 seconds then close again

I used "set interval" to do this function by :

    var rVars = []
    rVars.push( {name:"door", val:1} ) // 1 for open , 0 for close

  _server.setRoomVariables(r, user, rVars)
  var params = {}
  params.user = user
  params.r = r
  
  myInterval = setInterval("TimeForClose", 20000, params)

This is the code responsible for closing the door after 10 seconds

function TimeForClose(params){

    var rVars = []
    rVars.push( {name:"door", val:0} )

  _server.setRoomVariables(params.r, params.user, rVars)}

And it was done successfully, but the problem was that I found the function "TimeForclose" repeats every 10 seconds , which makes when another user click on the button and door opens for him, the first one repeated function which still repeats will close the door for the second user too and both functions of each of them will be repeated , and so on .

So I read I have to use "clear interval" or timer to stop repeating but when I used it, it didn't stop the repeating so I think I used it Incorrectly

So what's the best way to stop repeating? ( I just want the function to occurs once when someone click on a button then it stops ) .

I hope you give me the correct syntax of the code

2 Answers

Yes, as u said u can use clearInterval() after closing of that door window, try that once

If you need to only execute once, you can use setTimeout change setIntervalm to setTimeout

 myInterval =  setTimeout("TimeForClose", 20000, params)

The function is only executed once. If you need to repeat execution, use the setInterval() method.

If you need to repeat excution and stop based on some external event you can use clearTimeout()

Related