Chiew Soon How Chiew Soon How - 3 years ago 112
Javascript Question

How to run a function every 5 sec with difference value everytime?

i try to run a notification message on my page but i just wondering is there any siimple ways to code this?

<script>
window.setTimeout(function(){
iziToast.show({
hyperlink: '?id=002',
title: 'Title 2',
message: 'message 2',
image: 'img/2.jpg',
timeout: 7500,
});
}, 5000);

window.setTimeout(function(){
iziToast.show({
hyperlink: '?id=003',
title: 'Title 3',
message: 'message 3',
image: 'img/3.jpg',
timeout: 7500,
});
}, 17500);

window.setTimeout(function(){
iziToast.show({
hyperlink: '?id=004',
title: 'Title 4',
message: 'message 4',
image: 'img/4.jpg',
timeout: 7500,
});
}, 30000);

window.setTimeout(function(){
iziToast.show({
hyperlink: '?id=005',
title: 'Title 5',
message: 'message 5',
image: 'img/5.jpg',
timeout: 7500,
});
}, 42500);


</script>


How can i use much simple code to run those function? Sorry im very new in programming and self learner.

Answer Source

Maybe so:

var options = [
    {
        hyperlink: '?id=002',
        title: 'Title 2',
        message: 'message 2',
        image: 'img/2.jpg',
        timeout: 7500,
    },
    {
        hyperlink: '?id=003',
        title: 'Title 3',
        message: 'message 3',
        image: 'img/3.jpg',
        timeout: 7500,
    },
    {
        hyperlink: '?id=004',
        title: 'Title 4',
        message: 'message 4',
        image: 'img/4.jpg',
        timeout: 7500,
    },
    {
        hyperlink: '?id=005',
        title: 'Title 5',
        message: 'message 5',
        image: 'img/5.jpg',
        timeout: 7500,
    }
];

var timeout = [
    5000, 17500, 30000, 42500
];

for (var i = 0; i < options.length; i++) {
    window.setTimeout(function(){
        iziToast.show(options[i]);
    }, timeout[i]);
}

For another toast you can add an entry to options and a timeout to timeout array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download