I have just started learning javascript and I am in the process of creating a website where users can change the background by simply clicking on a button. It's working perfectly fine so far, but I want to add another feature where the background images cycle automatically after a certain time interval. Essentially, I want users to be able to manually change the background with a button click while also having a JavaScript loop running in the background to automatically click the same button at regular intervals. Is this feasible?
The current code for changing the background is shown below:
$(document).ready(function () {
var i = 0;
$("#n").click(function () {
i++;
if (i > 16) { i = 1; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
});
$("#p").click(function () {
i--;
if (i <= 0) { i = 16; };
$('body').css('background-image', 'url(img/' + i + '.jpg)');
});
});
And here are the buttons used in the code:
<button id="n" class="btn">Next</button>
<button id="p" class="btn">Previous</button>