I’m trying to delay the execution of the setInterval function, which is set at 2000.
Ideally, I would like the function to be executed after 10000 at every refresh of the page + after each hide on click function (that makes all the created divs disappear by clicking anywhere on the page and makes the function starts all over again).
Here’s how it looks like without any delay:
var list = ["ar1",
"ar2",
"ar3",
"ar4",
"ar5",
"ar6",
"ar7"];
var t = setInterval(createCat, 2000);
function createCat() {
var cat = $("<div>");
cat.addClass("ar1");
var index = Math.floor(Math.random() * list.length);
var catClass = list[ index ];
var cat = $("<div>");
cat.addClass(catClass);
var x = Math.random() * $(window).width();
var y = Math.random() * $(window).height();
cat.css("left",x);
cat.css("top",y);
// by clicking anywhere on the page the function disappears and starts all over again
$("body").click(function() {
cat.hide();
});
$("body").append(cat);
}
I tried delaying setInterval with the setTimeout function then clearing it out to make way for the setInterval function but it was unsuccessful and I can’t figure out why:
var timeout = setTimeout(function createCat(){
timeout = setTimeout(createCat, 10000);
}, 10000);
clearTimeout(timeout);
I have also tried the following but it did not work either:
let i = 1;
function createCat(value){
setTimeout(function(){
console.log("received value is : ",value)
},8000);
}