How stop a specified TimedLoop in JavaScript

时间:2017-04-10 00:07:16

标签: javascript

Right now my code looks something like this:

function shoot1() {
  timedLoop(10, function(a) {
    var lazorXposition = getXPosition("lazor1");
    if (Yposition >= -25) {
      showElement("lazor1");
      setPosition("lazor1", lazorXposition, Yposition - 4);
    } else {
  stopTimedLoop(a);
    }
  });
}

It's for a function that progressively moves an image across the screen. My problem is, is that every time the stopTimedLoop executes, every timed loop in my program stops. How would you specify which timed loop for the stopTimedLoop to stop? I know you can do it, but I can't seem to figure out how, in the above code, I've tried identifying the timed loop, but even though I specify that in the stopTimedLoop command, it still stops all functions that are currently looping. I'm currently trying to use AppLab from code.org to make a simple program, and this is what the website states for the stopTimedLoop command: Parameters

Name Type Required? Description loop Number The value returned by the timedLoop() function that you want stop. If not included, all running timed loops will stop. Tips

Without a parameter, all running timed loops will be stopped. If you want to stop a specific loop you need to save the value returned by timedLoop(), eg var i = timedLoop(ms, callback);

1 个答案:

答案 0 :(得分:1)

It sounds like you need to save the reference to the timed loop, and use pass that as an argument to the stopTimedLoop function. I would try the following:

function shoot1() {
  var thisLoop = timedLoop(10, function(a) {
    var lazorXposition = getXPosition("lazor1");
    if (Yposition >= -25) {
      showElement("lazor1");
      setPosition("lazor1", lazorXposition, Yposition - 4);
    } else {
  stopTimedLoop(thisLoop);
    }
  })

; }