简体   繁体   中英

I need help creating a loop in dev console in firefox

I am trying to use the dev console to give mario a mushroom every 5 seconds (in the browser game super mario html5)

I can give mario mushrooms manually by typing marioShroons(mario) but I would like to have it on loop so I don't have to pause the game every time I want a mushroom. I have tried a while loop and set timeout but I can't figure it out. The only coding languages I familiar with are c++ and html. **

while(data.time.amount > 0) {
  killOtherCharacters()
}

setTimeout(function() {
  killOtherCharacters()
}, 1000);

I expected these lines of code to not give me a mushroom, but to automatically kill enemies. But on the first try (the while loop) it froze the tab and I had to reload the page.

With the set timeout, it didn't make any obvious results, it killed all near characters once and then stopped.

The reason your while loop froze the page is because Javascript can only do one thing at a time and you told it to always run your while function, blocking all other Javascript from running on your site.

setTimeout is only run once after a set time ( see documentation ), if you want to run something every x miliseconds it's better to use setInterval instead .

var intervalID = window.setInterval(killOtherCharacters(), 500); //run this every 500 ms

Use setInterval if you want killOtherCharacters() to be called repeatedly.

const interval = setInterval(function() {killOtherCharacters() },1000);

Then when you want the function to stop being called:

clearInterval(interval);

You tried using setTimeout , and it only worked once. This is to be expected, because:

Window.setTimeout() sets a timer which executes a function or specified piece of code once the timer expires

From MDN

What you need to do is use setInterval :

The setInterval() method...repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

From MDN

So in your console, you should write this:

setInterval(killOtherCharacters, 1000);

(I removed the anonymous function because it wasn't needed - you only need an anonymous function if you're passing parameters or doing multiple things. You do need to remove the () for this though).

And if you want to stop the function from executing, assign a variable to the interval:

var killCharacters = setInterval(killOtherCharacters, 1000);

Then call clearInterval upon this variable to clear the interval (stop the loop):

clearInterval(killCharacters);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM