Search code examples
javascriptbookmarklet

Interval in JavaScript bookmarlet


I am playing around with bookmark snippets and I am trying to make a loop that changes the background color rapidly. This is my code:

var one;
funtion two() {
  document.body.style.backgroundColor = "#" + Math.floor(Math.random() * 1000);
  setTimeout(two, 1);
}
void 0

I am not very good at coding, so I am trying to make it very simple.


Solution

  • I submitted this snippet as an edit also, but I'm not entirely sure how those work. So I'm also submitting it as answer also. I've accomplished what you want by editing your original code as little as possible. Here's what I changed.

    1. function was spelled funtion
    2. You needed to use setInterval instead of setTimeout
    3. You needed to then initiate that setInterval from outside the function two() you are calling it from: `setInterval(two, 1)
    4. As others have mentioned, you can change the number 1 at the end to any other number of milliseconds you want it to hold each color for.

    var one;
    function two() {
      document.body.style.backgroundColor = "#" + Math.floor(Math.random() * 1000);
    };
    setInterval(two, 1);

    Cheers!