How to restart a setInterval loop in JavaScript

Recently, I created my own version of the "10 PRINT" project to enhance my JavaScript skills.

As a finishing touch, I decided to incorporate sliders that would allow viewers to adjust various parameters and witness the impact it has on the project.

You can check out my creation here: 10PRINT, developed by Boguz, hosted on GitHub

One slider I attempted to include was meant to control the speed of the animation, but unfortunately, I encountered issues getting it to function properly.

To initiate the animation, I relied on a setInterval method like this:

setInterval(function(speed){
    draw();
}, speed);

The speed variable is set when the document loads:

let speed = 50;

Subsequently, I attempted to update it (when a viewer interacts with the slider) using the following code:

const speedControl = document.querySelector("#speed-slider");
speedControl.oninput = function() {
    let speedVal = speedControl.value;
    speed = Number(speedVal);
    resetDraw();
}

Upon logging the speed variable in the console, I noticed that it contained the correct values; however, it did not produce the desired outcome.

If more code inspection is required, please feel free to request it or visit the GitHub Repository.

Any assistance or guidance would be greatly appreciated. Thank you!

Answer №1

Remember to store the value of setInterval in your script so that you can easily clear it later on.

// STORE INTERVAL VALUE
let drawInterval = setInterval(function(){
        draw();
}, speed);

When resetting your drawing, be sure to clear the interval first and then set it again with the new speed.

function resetDraw() {
    context.clearRect(0, 0, canvas.width, canvas.height);   
    xpos = 0;
    ypos = 0;
    draw();
    clearInterval(drawInterval);
    drawInterval = setInterval(draw, speed);
}

If you prefer, you can skip using the initial setInterval altogether and simply call resetDraw to get started.

Answer №2

Start fresh by clearing the old one before creating a new instance

function createNewInterval(newSpeed) {
    const intervalIdentifier = setInterval(function(){
        redraw();
    }, newSpeed);
    return intervalIdentifier;
}


let newIntervalIdentifier = createNewInterval(newSpeed);

...oninput = function() {
    clearInterval(newIntervalIdentifier);
    let updatedSpeedValue = speedControl.value;
    newSpeed = Number(updatedSpeedValue);
    newIntervalIdentifier = createNewInterval(updatedSpeedValue);
}

The duration of the interval set in setInterval cannot be modified while it's running, as it is determined at the time of calling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the inconsistency in time intervals in the loop?

My goal was to create a simple slider that loops through 3 images, with each image staying visible for 3 seconds before fading out and the next one fading in. However, I encountered an issue: The first image can stay for 3 seconds, but once the loop star ...

Transmit information and control instructions to an executing Puppeteer script

I'm a beginner when it comes to using Puppeteer and I've encountered a few issues while working with it. My main goal is to have the script respond to user input, such as changing pages or displaying element contents while it's running. The ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

What method can I use to ensure that the sidebar stays fixed at a particular div as the user continues to scroll down the

Is there a way to automatically fix the sidebar once the user scrolls down and hits the top of the .Section2? Currently, I have to manually enter a threshold number which can be problematic due to varying positions across browsers and systems. Fiddle htt ...

Getting command line argument parameters in React can be achieved by utilizing the `process.argv`

Is there a way to retrieve command line argument parameters in React? I currently have a React codebase that is utilizing Webpack. When running the following commands - npm run build -- --configuration=dev or npm run build -- --configuration=qa I need t ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

"Enhance your Three.js experience with the MeshPhongMaterial and

I'm having trouble adding a texture to a MeshPhongMaterial in Three.js. When I try to do so, all I get is a black box with some lighting effects. I've been stuck on this issue for quite some time and can't seem to find a solution. //Setting ...

AngularJS toaster doesn't seem to be appearing

I have integrated the angularjs toaster library into my project. Here are the necessary references: https://github.com/jirikavi/AngularJS-Toaster Added the following references for the library: <link rel="stylesheet" href="bower_components/Angu ...

Guide to importing a JSON file in a Node.js JavaScript file

I am trying to incorporate a JSON file into my JavaScript code in a Node.js application. I attempted to include it using the "require();" method, but encountered an issue: "Uncaught ReferenceError: require is not defined". ...

The submission of the form using AJAX is currently experiencing issues

My current issue involves ajax not functioning as intended. I have a form that is being submitted through ajax to my php file for the purpose of updating my database. The database update is successful, but there seems to be a problem with the ajax function ...

I am experiencing an issue wherein after using jquery's hover() function, the CSS :hover state is not

Following the jquery hover function, the css hover feature ceases to work. In my html, there are multiple svg elements. A jquery script is applied where hovering over a button at the bottom triggers all svg elements to change color to yellow (#b8aa85). S ...

Is there a way to successfully integrate a JavaScript file that has been downloaded from `npm` or `yarn` into a web client or

Currently, I am following a guide titled "Headless Drupal with React" on Medium. The tutorial itself does not address my specific questions. In the tutorial, it demonstrates importing React and ReactDOM directly from CDN in the .html file. My query revolv ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Is a finished callback needed for .on('xxx') event?

On my dashboard page, I am currently retrieving the top 25 comments and displaying them using the following code: fba.orderByChild('when').limitToLast(25).on('child_added', function (d, c) { stuff }); However, the function is called f ...

Struggling to locate the element value in Puppeteer? Reach out for assistance with await page.waitForSelector() or await page.waitForXPath()

insert image description here[ await page.waitForSelector('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW'); await page.type('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW','01- ...

Guide on transferring data from a JavaScript input to Flask

I have a table with buttons assigned to each row. Upon clicking a button, such as row 3, the ID corresponding to that row will be displayed in an alert message as well as logged in the console. My ultimate goal is to transmit this row ID to Flask Python so ...

Unexpected outcomes can arise from rotating looped meshes

In my current three.js project, I am working with a total of 100 meshes which are organized into 10 different scenes: // Adding 100 meshes to 10 scenes based on an array containing 100 elements for (var i = 0; i < data.length; i++) { mesh = new ...

Issue with Angular Promise ($q) functionality being non-operational

I am currently experimenting with integrating Angular and SignalR in a demo application. I have attempted to implement promises using the $q service, but for some reason my code is not functioning as expected. SERVICE var boardConsole = $.connection.buil ...

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...

Ways to customize pixel scrolling on page reload or through the use of a hyperlink to a specific tab in a page

I have implemented a Bootstrap panel using the following code: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab&qu ...